1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
private void WriteExcel(string filePath) { if (!string.IsNullOrEmpty(filePath)) { NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("export");
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0); int[] columnWidth = { 8, 8, 8, 8, 30, 30, 8, 8, 8, 8 }; for (int i = 0; i < columnWidth.Length; i++) { row.CreateCell(i).CellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
sheet.SetColumnWidth(i, columnWidth[i] * 256);
row.Height = 15 * 20; }
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 10));
row.GetCell(0).SetCellValue("合并的单元格");
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(1); row2.Height = 28 * 20;
string[] columnName = { "编号", "标题", "标题", "标题", "长……长……的……标……题……", "长……长……的……标……题……", "标题", "标题", "标题", "标题" };
for (int i = 0; i < columnName.Length; i++) { row2.CreateCell(i).CellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; row2.CreateCell(i).SetCellValue(columnName[i]); }
for (int i = 0; i < 10; i++) { NPOI.SS.UserModel.IRow rowDetail = sheet.CreateRow(i + 2); rowDetail.Height = 70 * 20; rowDetail.CreateCell(i).CellStyle.WrapText = true;
rowDetail.CreateCell(0).SetCellValue((i + 1).ToString()); rowDetail.CreateCell(1).SetCellValue("内容"); rowDetail.CreateCell(2).SetCellValue("内容"); rowDetail.CreateCell(3).SetCellValue("内容"); rowDetail.CreateCell(4).SetCellValue("好……多……好……多……好……多……的……内……容……好……多……好……多……好……多……的……内……容……好……多……好……多……好……多……的……内……容……"); rowDetail.CreateCell(5).SetCellValue("好……多……好……多……好……多……的……内……容……好……多……好……多……好……多……的……内……容……好……多……好……多……好……多……的……内……容……"); rowDetail.CreateCell(6).SetCellValue("内容"); rowDetail.CreateCell(7).SetCellValue("内容"); rowDetail.CreateCell(8).SetCellValue("内容"); rowDetail.CreateCell(9).SetCellValue("内容"); }
using(System.IO.MemoryStream ms = new System.IO.MemoryStream()) { book.Write(ms); using(FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } book = null; } } }
|