1. 程式人生 > 其它 >C# 使用NPOI生成Excel檔案

C# 使用NPOI生成Excel檔案

nuget 引入NPOI

            IWorkbook wk = new HSSFWorkbook();

            // 設定樣式
            ICellStyle cellStyle = wk.CreateCellStyle();
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;

            
// 建立Sheet ISheet sheet = wk.CreateSheet("報文資料"); // 設定單元的寬度 sheet.SetColumnWidth(0, 10 * 256); sheet.SetColumnWidth(1, 15 * 256); sheet.SetColumnWidth(2, 15 * 256); sheet.SetColumnWidth(3, 15 * 256); sheet.SetColumnWidth(
4, 65 * 256); // 寫入一行資料 int rowIndex = 0; IRow row = sheet.CreateRow(rowIndex); row.CreateCell(0).SetCellValue("序號"); row.CreateCell(1).SetCellValue("時間"); row.CreateCell(2).SetCellValue("名稱"); row.CreateCell(
3).SetCellValue("幀ID(HEX)"); row.CreateCell(4).SetCellValue("資料(HEX)"); row.CreateCell(5).SetCellValue(" "); rowIndex++; // 迴圈寫入資料 for (int i = 0; i < 100; i++) { row = sheet.CreateRow(rowIndex); row.CreateCell(0).SetCellValue(rowIndex); rowIndex++; } // 生成檔案,寫入資料 (確保你資料夾存在) using (FileStream fswrite = File.OpenWrite($"Excel/test/test.xls")) { wk.Write(fswrite); }

結果