【发布时间】:2017-12-13 05:37:10
【问题描述】:
我正在使用 EPPlus 在我的 MVC 项目中创建一个 Excel 文件。我想创建一个包含 30 列的电子表格。
使用我当前的代码,电子表格最多有 26 列(名为 A - Z)。我知道我需要更改范围以包括 AA - ZZ 列,但我不知道该怎么做。我应该用 int 来引用列吗?我在 GitHub 网站上没有看到任何这样的示例。
这是我的代码(Excel 数据来自数据表 (dt)):
//return dt;
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Claims");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(dt, true);
//prepare the range for the column headers
string cellRange = "A1:" + Convert.ToChar('A' + dt.Columns.Count - 1) + 1;
//Format the header for columns
using (ExcelRange rng = ws.Cells[cellRange])
{
rng.Style.WrapText = false;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
//Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Yellow);
rng.Style.Font.Color.SetColor(Color.Black);
}
//prepare the range for the rows
string rowsCellRange = "A2:" + Convert.ToChar('A' + dt.Columns.Count - 1) + dt.Rows.Count * dt.Columns.Count;
//Format the rows
using (ExcelRange rng = ws.Cells[rowsCellRange])
{
rng.Style.WrapText = true;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
}
//Read the Excel file in a byte array
Byte[] fileBytes = pck.GetAsByteArray();
//Clear the response
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment;filename=Claims.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Write it back to the client
Response.BinaryWrite(fileBytes);
Response.End();
}
【问题讨论】:
-
使用整数。格式:“ws.Cells[row, column]”
-
我能够简单地转换为 ws.Cells[1,1] 以使其正常工作,但是如何格式化标题行呢?我的第一行/标题行是粗体文本,背景为黄色。我现在该如何解决这个问题(请参阅上面的代码//Format the header for columns comment)。我收到此错误 -{"Invalid Address format ]1"} on line: using (ExcelRange rng = ws.Cells[cellRange]
-
using (var range = ws.Cells[1, 1, 1, 11]) //格式:ws.Cells[int FromRow, int FromCol, int ToRow, int ToCol] { range.Style .Font.Bold = true; range.Style.ShrinkToFit = false; range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; range.AutoFilter = true; }
-
太棒了!谢谢!如果你想发布这个,我会选择它作为答案。
标签: c# asp.net-mvc epplus