C# Excel导出(使用EPPlus)

一笑奈何 提交于 2020-01-30 21:27:36
            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  )

 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!