using (ExcelPackage package = new ExcelPackage(new FileInfo(@"C:\test.xlsx"))) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");//创建worksheet worksheet.Name = "交通"; // worksheet.Cells[1, 1].Value = "名称";//直接指定行列数进行赋值 worksheet.Cells["A1"].Value = TableName;//直接指定单元格进行赋值 worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中 worksheet.Cells[1, 1, 1, dt.Columns.Count].Merge = true;//合并单元格 worksheet.Cells["A2"].Value = "报表时间:" + det.ToString("yyyy年MM月dd日");//直接指定单元格进行赋值 worksheet.Cells[2, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;//居中向右 worksheet.Cells[2, 1, 2, dt.Columns.Count].Merge = true;//合并单元格 foreach (DataColumn item in dt.Columns) { int a = item.Ordinal + 1; worksheet.Cells[3, a].Value = item.ColumnName; } int row = 4; foreach (DataRow item in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { worksheet.Cells[row, i + 1].Value = item[i].ToString(); } row++; }
使用了EPPlus,需nuget安装( Install-Package EPPlus )
来源:https://www.cnblogs.com/xianyv/p/11949684.html