【问题标题】:EPPlus - Write Excel File with more than 26 columns, C#/MVCEPPlus - 编写超过 26 列的 Excel 文件,C#/MVC
【发布时间】: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.Horizo​​ntalAlignment = ExcelHorizo​​ntalAlignment.Center; range.AutoFilter = true; }
  • 太棒了!谢谢!如果你想发布这个,我会选择它作为答案。

标签: c# asp.net-mvc epplus


【解决方案1】:

使用整数以方便使用。 格式:"ws.Cells[row, column]"

使用此代码设置标题:

                using (var range = ws.Cells[1, 1, 1, 11])  //format: 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;
            }

【讨论】:

    【解决方案2】:

    首先,正如我在您的 cmets 中看到的那样,workSmarter 说您可以使用ws.Cells[row,col] 格式来寻址单元格。 但您也可以使用 EPPlus 在 Excel 中加载通用 IEnumerable (IEnumerable)。这是一种使用LoadFromCollection 方法在Excel 中编写通用IEnumerable 的方法。在此示例中,我使用反射基于 T 属性创建标题行:

    public FileContentResult WriteToExcel<T>(IEnumerable<T> data, string fileName, bool shouldGenerateSumRow = true)
        {
            using (var package = new ExcelPackage())
            {
    
                var ws = package.Workbook.Worksheets.Add("گزارش");
                ws.View.RightToLeft = true;
                var props = TypeDescriptor.GetProperties(typeof(T));
                var RowCount = data.Count();
    
                ws.Cells.LoadFromCollection(data, true, OfficeOpenXml.Table.TableStyles.Medium27);
                ws.InsertRow(1, 1);
                var excelRange = ws.Cells[1, 1, 1, props.Count];
                ws.Row(1).Height = 80;
    
                excelRange.Merge = true;
                excelRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous;
                excelRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                excelRange.Style.WrapText = true;
                excelRange.Value = fileName;
    
                for (var i = 0; i < props.Count; i++)
                {
                    ws.Cells[2, i + 1].Value = props[i].DisplayName;
                }
    
    
                ws.Cells.AutoFitColumns();
    
                var fcr = new FileContentResult(package.GetAsByteArray(),
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    FileDownloadName = $"{fileName}.xlsx"
                };
                return fcr;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多