public void ExportExcel(DataTable dt)
{
//要添加epplus的nuget包
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;//epplus的5.0版本以上的要加这行非商用声明
//新建一个 Excel 工作簿
ExcelPackage package = new ExcelPackage();
// 添加一个 sheet 表
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dt.TableName);
int rowIndex = 1; // 起始行为 1
int colIndex = 1; // 起始列为 1
//设置列名
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[rowIndex, colIndex + i].Value = dt.Columns[i].ColumnName;
//自动调整列宽,也可以指定最小宽度和最大宽度
worksheet.Column(colIndex + i).AutoFit();
}
// 跳过第一列列名
rowIndex++;
//写入数据
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[rowIndex + i, colIndex + j].Value = dt.Rows[i][j].ToString();
}
//自动调整行高
worksheet.Row(rowIndex + i).CustomHeight = true;
}
//设置字体,也可以是中文,比如:宋体
worksheet.Cells.Style.Font.Name = "Arial";
//字体加粗
worksheet.Cells.Style.Font.Bold = true;
//字体大小
worksheet.Cells.Style.Font.Size = 12;
//字体颜色
//worksheet.Cells.Style.Font.Color.SetColor(System.Drawing.Color.Black);
//单元格背景样式,要设置背景颜色必须先设置背景样式
//worksheet.Cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
//单元格背景颜色
//worksheet.Cells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.DimGray);
//设置单元格所有边框样式和颜色
//worksheet.Cells.Style.Border.BorderAround(ExcelBorderStyle.Thin, System.Drawing.ColorTranslator.FromHtml("#0097DD"));
//单独设置单元格四边框 Top、Bottom、Left、Right 的样式和颜色
//worksheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
//worksheet.Cells.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
//垂直居中
worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
//水平居中
worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
//单元格是否自动换行
worksheet.Cells.Style.WrapText = false;
//设置单元格格式为文本
worksheet.Cells.Style.Numberformat.Format = "@";
//单元格自动适应大小
worksheet.Cells.Style.ShrinkToFit = true;
//worksheet.Dispose();
//package.Dispose();
////第一种保存方式
//string path1 ="";
//string filePath1 = path1 + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
//FileStream fileStream1 = new FileStream(filePath1, FileMode.Create);
////保存至指定文件
//FileInfo fileInfo = new FileInfo(filePath1);
//package.SaveAs(fileInfo);
////第二种保存方式
string path2 = ""; /*HttpContext.Current.Server.MapPath("Export/");*/
string filePath2 = path2 + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
FileStream fileStream2 = new FileStream(filePath2,FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
//写入文件流
package.SaveAs(fileStream2);
//创建一个内存流,然后转换为字节数组,输出到浏览器下载
//MemoryStream ms = new MemoryStream();
//package.SaveAs(ms);
//byte[] bytes = ms.ToArray();
//也可以直接获取流
//Stream stream = package.Stream;
//也可以直接获取字节数组
byte[] bytes = package.GetAsByteArray();
//调用下面的方法输出到浏览器下载
//OutputClient(bytes);
fileStream2.Flush();
fileStream2.Close();
worksheet.Dispose();
package.Dispose();
}