C# NPOI读写XLSX文件
//NPOI读取XLSX格式读取流,需要重新创建流写入
//nuget: NPOI 2.4.1 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Data; using System.IO; namespace ExcelExport { class Program { static void Main(string[] args) { string path = @"1.xlsx"; DataTable dt = GetDataTable(); DataTableToExcel(dt, path); } private static DataTable GetDataTable() { var dt = new DataTable("cart"); DataColumn dc1 = new DataColumn("prizename", Type.GetType("System.String")); DataColumn dc2 = new DataColumn("point", Type.GetType("System.Int16")); DataColumn dc3 = new DataColumn("number", Type.GetType("System.Int16")); DataColumn dc4 = new DataColumn("totalpoint", Type.GetType("System.Int64")); DataColumn dc5 = new DataColumn("prizeid", Type.GetType("System.String")); DataColumn dc6 = new DataColumn("Timer", Type.GetType("System.DateTime")); dt.Columns.Add(dc1); dt.Columns.Add(dc2); dt.Columns.Add(dc3); dt.Columns.Add(dc4); dt.Columns.Add(dc5); dt.Columns.Add(dc6); //以上代码完成了DataTable的构架,但是里面是没有任何数据的 //Random r = new Random(); for (int i = 0; i < 10; i++) { //int a = r.Next(1, 100); DataRow dr = dt.NewRow(); dr["prizename"] = "娃娃" + i; dr["point"] = 10; dr["number"] = i; dr["totalpoint"] = 10; dr["prizeid"] = "001"; dr["Timer"] = DateTime.Now.AddDays(i); dt.Rows.Add(dr); } return dt; } public static bool DataTableToExcel(DataTable dt,string path) { bool result = false; IWorkbook workbook = null; FileStream fs = null; IRow row = null; ISheet sheet = null; ICell cell = null; try { if (dt != null && dt.Rows.Count > 0) { using (fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) { workbook = new XSSFWorkbook(fs); sheet = workbook.GetSheetAt(0);//创建一个名称为Sheet0的表 int rowCount = dt.Rows.Count;//行数 int columnCount = dt.Columns.Count;//列数 //设置每行每列的单元格, for (int i = 0; i < rowCount; i++) { row = sheet.CreateRow(i + 9);//从第多少行开始写 for (int j = 0; j < columnCount; j++) { cell = row.CreateCell(j);//excel第二行开始写入数据 cell.SetCellValue(dt.Rows[i][j].ToString()); } } using(var file2 = new FileStream(@"..\2.xlsx", FileMode.Create,FileAccess.ReadWrite)){ workbook.Write(file2); file2.Close(); } workbook.Write(fs); result = true; } } return result; } catch (Exception ex) { if (fs != null) { fs.Close(); } return false; } } } }