基於NPOI操作Excel
阿新 • • 發佈:2022-03-08
/// <summary> /// 基於NPOI操作Excel /// </summary> public void ExportExcel() { string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Excel\\"; string fileName = filePath + "TestExcel_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ".xlsx"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { XSSFWorkbook workbook = new XSSFWorkbook(); //建立單元格樣式 ICellStyle cellStyle = workbook.CreateCellStyle(); //設定為文字格式,也可以為 text,即 dataFormat.GetFormat("text"); cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; //下邊框線 cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; //左邊框線 cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; //右邊框線 cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; //上邊框線 //設定頁簽名 ISheet sheet = workbook.CreateSheet("匯出號段"); //設定列寬 sheet.SetColumnWidth(4, 10 * 500);//第五列 BTMAC sheet.SetColumnWidth(5, 10 * 500);//第六列 WifiMAC1 sheet.SetColumnWidth(6, 10 * 500);//第七列 WifiMAC2 sheet.SetColumnWidth(7, 10 * 500);//第八列 HARD_CODE sheet.SetColumnWidth(8, 10 * 500);//第九列 QR_CODE //Excel表頭欄位 string[] excelHeader = new string[] { "IMEI1", "IMEI2", "MEID", "MSN編號", "藍芽MAC地址", "無線MAC地址1", "無線MAC地址2", "HARD_CODE", "QR_CODE", "TOKEN", "KEYMASTER" }; //設定表頭欄位 IRow headerRow = sheet.CreateRow(0); for (int i = 0; i < excelHeader.Length; i++) { headerRow.CreateCell(i).SetCellValue(excelHeader[i]); } //展開的數量 int count = int.Parse(LoginInfo.QTY); //十六進位制轉為十進位制 Int64 StarthardCode = Int64.Parse(LoginInfo.HardCode, NumberStyles.HexNumber); Int64 StartbtMAC = Int64.Parse(LoginInfo.BTMAC, NumberStyles.HexNumber); Int64 StartWifiMAC1 = Int64.Parse(LoginInfo.WiFiMAC1, NumberStyles.HexNumber); Int64 StartWifiMAC2 = 0; if (LoginInfo.IsEnableWiFiMAC2) { StartWifiMAC2 = Int64.Parse(LoginInfo.WiFiMAC2, NumberStyles.HexNumber); } //填充Excel for (int i = 0; i < count; i++) { IRow row = sheet.CreateRow(i + 1); //BTMAC Int64 current_btMAC = StartbtMAC + i; //轉回十六進位制,大寫 //string strCurrent_btMAC = Convert.ToString(current_btMAC, 16).ToUpper(); string strCurrent_btMAC = current_btMAC.ToString("X").ToUpper(); row.CreateCell(4).SetCellValue(strCurrent_btMAC); //WifiMAC1 Int64 current_WifiMAC1 = StartWifiMAC1 + i; //轉回十六進位制,大寫 string strCurrent_WifiMAC1 = current_WifiMAC1.ToString("X").ToUpper(); row.CreateCell(5).SetCellValue(strCurrent_WifiMAC1); //WifiMAC2 if (LoginInfo.IsEnableWiFiMAC2) { Int64 current_WifiMAC2 = StartWifiMAC2 + i; //轉回十六進位制,大寫 string strCurrent_WifiMAC2 = current_WifiMAC2.ToString("X").ToUpper(); row.CreateCell(6).SetCellValue(strCurrent_WifiMAC2); } //HardCode Int64 current_HardCode = StarthardCode + i; //轉回十六進位制,小寫 string strCurrent_HardCode = current_HardCode.ToString("X").ToLower(); row.CreateCell(7).SetCellValue(strCurrent_HardCode); } workbook.Write(fs); //寫入到Excel中 } }