1. 程式人生 > 實用技巧 >C# NPOI操作EXCEL之寫資料、設定單元格樣式、合併單元格、插入圖片

C# NPOI操作EXCEL之寫資料、設定單元格樣式、合併單元格、插入圖片

這段時間做專案,剛好碰到需要往Excel寫資料,網上的資料零零散散,故自己花時間整理下。已測試過可直接執行。

1.涉及檔案:NPOI.dll、NPOI.OOXML.dll、NPOI.OpenXml4Net.dll、NPOI.OpenXmlFormats.dll、NPOI.xml、ICSharpCode.SharpZipLib.dll

using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

2.往EXCEL寫資料、合併單元格、設定字型樣式、插入圖片

namespace
Task_Test { public class ExcelHelper { public static void WriteExcel() { string templateFile = @"C:\test\temple.xlsx"; // 檔案必須存在 string outFile = @"C:\test\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx"; string picPath = @"C:\test\test.jpg
"; IWorkbook workbook = null; FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read); if (Path.GetExtension(templateFile) == ".xls") { workbook = new HSSFWorkbook(file); } else if (Path.GetExtension(templateFile) == "
.xlsx") { workbook = new XSSFWorkbook(file); } ISheet sheet = workbook.GetSheetAt(0); try { SetCellValue(sheet, 0, 0, "這裡是第1行第1列內容"); SetCellValue(sheet, 0, 1, "這裡是第1行第2列內容"); SetCellValue(sheet, 1, 0, "這裡是第2行第1列內容"); SetCellValue(sheet, 1, 1, "這裡是第2行第2列內容"); // Height:單位是1/20個點,所以要想得到一個點的話,需要乘以20。 sheet.GetRow(1).Height = 44 * 20; // 給第2行設定行高 // Width: 單位是1/256個字元寬度,所以要乘以256才是一整個字元寬度 sheet.SetColumnWidth(1, 50 * 256); // 給第1列設定寬度 SetCellValue(sheet, 2, 0, "這裡是第3行第1列內容,需要設定字型樣式"); // 從第3行到第6行,第1列到第4列合併單元格 SetCellRangeAddress(sheet, 2, 5, 0, 3); // 給合併之後的單元格加邊框,並設定字型大小、居中、字型顏色、背景色 AddRengionBorder(workbook, sheet, 2, 5, 0, 3); // 插入圖片 InsertFootSignPic(workbook, sheet, 7, 16, 0, 2, outFile, picPath); } catch (Exception ex) { throw ex; } finally { if (file != null) { file.Close(); } } } /// <summary> /// 單元格設定內容 /// </summary> /// <param name="sheet"></param> /// <param name="rowIndex">第幾行,從0開始</param> /// <param name="cellIndex">第幾列,從0開始</param> /// <param name="value">內容(字串)</param> public static void SetCellValue(ISheet sheet, int rowIndex, int cellIndex, string value) { if (sheet.GetRow(rowIndex) == null) { sheet.CreateRow(rowIndex); } if (sheet.GetRow(rowIndex).GetCell(cellIndex) == null) { sheet.GetRow(rowIndex).CreateCell(cellIndex); } sheet.GetRow(rowIndex).GetCell(cellIndex).SetCellValue(value); } /// <summary> /// 合併單元格 /// </summary> /// <param name="sheet">要合併單元格所在的sheet</param> /// <param name="rowstart">開始行的索引</param> /// <param name="rowend">結束行的索引</param> /// <param name="colstart">開始列的索引</param> /// <param name="colend">結束列的索引</param> public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend) { for (int r = rowstart; r <= rowend; r++) { for (int c = colstart; c <= colend; c++) { if (sheet.GetRow(r) == null) { sheet.CreateRow(r); // 如果行不存在,則建立行 } if (sheet.GetRow(r).GetCell(c) == null) { sheet.GetRow(r).CreateCell(c); // 如果列不存在,則建立列 } } } NPOI.SS.Util.CellRangeAddress cellRangeAddress = new NPOI.SS.Util.CellRangeAddress(rowstart, rowend, colstart, colend); sheet.AddMergedRegion(cellRangeAddress); } /// <summary> /// 加範圍邊框和設定字型大小、顏色、背景色、居中 /// </summary> /// <param name="firstRow">起始行</param> /// <param name="lastRow">結束行</param> /// <param name="firstCell">起始列</param> /// <param name="lastCell">結束列</param> /// <returns></returns> public static void AddRengionBorder(IWorkbook workbook, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell) { for (int i = firstRow; i < lastRow; i++) { for (int n = firstCell; n < lastCell; n++) { ICell cell; cell = sheet.GetRow(i).GetCell(n); if (cell == null) { cell = sheet.GetRow(i).CreateCell(n); } ICellStyle style = sheet.Workbook.CreateCellStyle(); style.BorderTop = BorderStyle.Thin; style.BorderBottom = BorderStyle.Thin; style.BorderLeft = BorderStyle.Thin; style.BorderRight = BorderStyle.Thin; style.Alignment = HorizontalAlignment.Center; //水平對齊 :居中 style.VerticalAlignment = VerticalAlignment.Center; //垂直對齊 :居中 if (i == firstRow) //第一行 { style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index; // 背景色:黑色 style.FillPattern = FillPattern.SolidForeground; IFont font = workbook.CreateFont(); //建立一個字型顏色 font.Color = NPOI.HSSF.Util.HSSFColor.White.Index; //字型顏色:白色 font.FontHeightInPoints = 18;//字型大小 style.SetFont(font); //給樣式設定字型 } cell.CellStyle = style; } } } /// <summary> /// 往EXCEL指定單元格插入圖片 /// </summary> /// <param name="workbook"></param> /// <param name="sheet"></param> /// <param name="firstRow"> 起始單元格行序號,從0開始計算</param> /// <param name="lastRow"> 終止單元格行序號,從0開始計算</param> /// <param name="firstCell"> 起始單元格列序號,從0開始計算</param> /// <param name="lastCell"> 終止單元格列序號,從0開始計算</param> /// <param name="outFile">插入圖片後,另存為路徑(絕對路徑)</param> /// <param name="picurl">圖片絕對路徑</param> public static void InsertFootSignPic(IWorkbook workbook, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell, string outFile, string picurl) { FileStream filess = null; try { // 將圖片轉換為位元組陣列 byte[] bytes = System.IO.File.ReadAllBytes("" + picurl + ""); int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG); XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch(); // dx1:起始單元格的x偏移量,如例子中的255表示直線起始位置距A1單元格左側的距離; // dy1:起始單元格的y偏移量,如例子中的125表示直線起始位置距A1單元格上側的距離; // dx2:終止單元格的x偏移量,如例子中的1023表示直線起始位置距C3單元格左側的距離; // dy2:終止單元格的y偏移量,如例子中的150表示直線起始位置距C3單元格上側的距離; // col1:起始單元格列序號,從0開始計算; // row1:起始單元格行序號,從0開始計算,如例子中col1 = 0,row1 = 0就表示起始單元格為A1; // col2:終止單元格列序號,從0開始計算; // row2:終止單元格行序號,從0開始計算,如例子中col2 = 2,row2 = 2就表示起始單元格為C3; XSSFClientAnchor anchor = new XSSFClientAnchor(10, 10, 0, 0, firstCell, firstRow, lastCell, lastRow); //把圖片插到相應的位置 XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); filess = File.OpenWrite(outFile); workbook.Write(filess); } catch (Exception ex) { throw ex; } finally { if (filess != null) { filess.Close(); } } } } }

3.執行後效果圖