要在C#中控制導(dǎo)出Excel并設(shè)置樣式,可以使用Excel操作庫(kù),例如EPPlus或NPOI。下面以EPPlus為例,提供一段示例代碼:
Install-Package EPPlus
using OfficeOpenXml;
using OfficeOpenXml.Style;
// 創(chuàng)建Excel文件
using (ExcelPackage excel = new ExcelPackage())
{
// 添加一個(gè)工作表
ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Sheet1");
// 設(shè)置單元格的值和樣式
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);
}
// 提供下載
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=excel_file.xlsx");
Response.BinaryWrite(excelBytes);
Response.End();
請(qǐng)確保替換代碼中的path_to_save_excel.xlsx
為你想要保存Excel文件的路徑。另外,你還可以根據(jù)需要設(shè)置更多的樣式,例如邊框、對(duì)齊等。