温馨提示×

C#中控制导出Excel,Excel样式的设置下载

c#
小云
90
2023-08-07 14:08:15
栏目: 编程语言

要在C#中控制导出Excel并设置样式,可以使用Excel操作库,例如EPPlus或NPOI。下面以EPPlus为例,提供一段示例代码:

  1. 首先,需要安装EPPlus库。在Visual Studio中,打开NuGet包管理器控制台,并运行以下命令:
Install-Package EPPlus
  1. 导入EPPlus命名空间:
using OfficeOpenXml;
using OfficeOpenXml.Style;
  1. 创建一个Excel文件并设置样式:
// 创建Excel文件
using (ExcelPackage excel = new ExcelPackage())
{
// 添加一个工作表
ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Sheet1");
// 设置单元格的值和样式
worksheet.Cells["A1"].Value = "Hello";
worksheet.Cells["A1"].Style.Font.Bold = true;
worksheet.Cells["A1"].Style.Font.Size = 14;
worksheet.Cells["B1"].Value = "World";
worksheet.Cells["B1"].Style.Font.Bold = true;
worksheet.Cells["B1"].Style.Font.Size = 14;
worksheet.Cells["B1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["B1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
// 保存Excel文件
byte[] excelBytes = excel.GetAsByteArray();
File.WriteAllBytes("path_to_save_excel.xlsx", excelBytes);
}
  1. 将创建的Excel文件提供给用户进行下载:
// 提供下载
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=excel_file.xlsx");
Response.BinaryWrite(excelBytes);
Response.End();

请确保替换代码中的path_to_save_excel.xlsx为你想要保存Excel文件的路径。另外,你还可以根据需要设置更多的样式,例如边框、对齐等。

0