NPOI匯出Excel中修改格式,傳輸圖片
一、使用NPOI設定背景色
方法一:使用NOPI自帶的顏色使用方法,缺點就是自帶的樣色種類少,不夠用
HSSFWorkbook hssfworkbook = new HSSFWorkbook();//建立工作薄
styleCommonTextRedColor = hssfworkbook.CreateCellStyle();//建立單元格
//新增顏色
styleCommonTextRedColor.FillPattern = FillPattern.SolidForeground;
styleCommonTextRedColor.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.PaleBlue.Index;
方法二:採用RGB顏色
HSSFWorkbook hssfworkbook = new HSSFWorkbook();//建立工作薄
styleCommonTextRedColor = hssfworkbook.CreateCellStyle();//建立單元格
//自定義顏色
HSSFPalette palette = hssfworkbook.GetCustomPalette();
palette.SetColorAtIndex(40, 250, 208, 121);//引數說明,第一個是指調色盤的位置,後三個引數是RGB色值
HSSFColor hssfColorY = palette.FindColor(250, 208, 121);
styleColorRed.FillPattern = FillPattern.SolidForeground;
styleColorRed.FillForegroundColor = hssfColorR.Indexed;
圖片傳輸:
byte[] bytes = System.IO.File.ReadAllBytes(@"....");
int pictureIdex = hssfworkbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.PNG);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 25, 158, 62, 0, 0, 0, 1);
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdex);
說明:
- public HSSFClientAnchor(int dx1,int dy1,int dx2,int dy2,short col1,int row1,short col2,
- int row2);Creates a new client anchor and sets the top-left and bottom-right coordinates of the anchor.
- Parameters:
- dx1 - the x coordinate within the first cell.
- dy1 - the y coordinate within the first cell.
- dx2 - the x coordinate within the second cell.
- dy2 - the y coordinate within the second cell.
dx2:第二個單元格的開始X座標
dy2:第二個單元格的開始y座標
- col1 - the column (0 based); of the first cell.
- row1 - the row (0 based); of the first cell.
- col2 - the column (0 based); of the second cell.
- row2 - the row (0 based); of the second cell.
- col1 圖片的左上角放在第幾個列cell,
row1 圖片的左上角放在第幾個行cell,
col2 圖片的右下角放在第幾個列cell,
row2 圖片的右下角放在第幾個行cell, - 列寬
sheet.setColumnWidth((short)column,(short)width);
行高
row.setHeight((short)height); - 新增多個圖片時:多個pic應該share同一個DrawingPatriarch在同一個sheet裡面。