要在C#中控制导出Excel并设置样式,可以使用Excel操作库,例如EPPlus或NPOI。下面以EPPlus为例,提供一段示例代码:
- 首先,需要安装EPPlus库。在Visual Studio中,打开NuGet包管理器控制台,并运行以下命令:
Install-Package EPPlus
- 导入EPPlus命名空间:
using OfficeOpenXml; using OfficeOpenXml.Style;
- 创建一个Excel文件并设置样式:
// 创建Excel文件 using (ExcelPackage excel = new ExcelPackage()) { // 添加一个工作表 ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Sheet1"); // 设置单元格的值和样式 worksheet.Cells["A1"].Value = "https://www.yisu.com/ask/Hello"; worksheet.Cells["A1"].Style.Font.Bold = true; worksheet.Cells["A1"].Style.Font.Size = 14; worksheet.Cells["B1"].Value = "https://www.yisu.com/ask/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); }
- 将创建的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文件的路径。另外,你还可以根据需要设置更多的样式,例如边框、对齐等。