C#EPPLUS:自动调整列到最大自动调整大小不起作用

时间:2018-05-30 09:33:56

标签: c# epplus

我正在使用EPPlus生成许多excel文档,我在格式化方面遇到了一些困难。

我用过

xlWorkSheet.Cells.AutoFitColumns();

这似乎适用于数据,但不会为列名自动调整大小。例如,我将打开文件,我可以看到列名称聚集。我也可以点击列的边框,它会更多地扩展列。事实上,在它达到自动调整的最大值之前,我可以做大约5次。基本上我想以编程方式设置每一列,使其达到最大值(我甚至尝试多次应用AutoFitColumns,但这并没有区别)。

有办法做到这一点吗?

请注意,我不能仅对列宽进行硬编码,因为我正在尝试为多个文件重用相同的代码。

编辑:这是我的代码概括

private void GeneralTest()
{
    var ReportName = "myReport"
    int ReportID = 123
    var SelectedMonth = "April 2018"
    var LAGroup = "all"
    var fileName = $"{ReportName}_{SelectedMonth}_{LAGroup}.xlsx";
    // Remove all illegal characters and replace with underscores
    var[] disallowedCharacters = new[] { "/", @"\", "?", "%", "*", ":", "|", "\"", "<", ">" };
    foreach (var character in disallowedCharacters)
        fileName = fileName.Replace(character, "_");

    var filePath = $@"c:\Test\{fileName}";
    if (File.Exists(filePath))
        File.Delete(filePath);
    FileInfo NewFile = new FileInfo(filePath);

    using (ExcelPackage MyExcel = new ExcelPackage(NewFile))
    {
        var myTestdt = MyGetDataFunction(ReportID, DateTime.Parse(SelectedMonth));
        ExcelWorksheet xlWorkSheet;

        xlWorkSheet = MyExcel.Workbook.Worksheets.Add("Template");
        xlWorkSheet.Name = "Template";

        xlWorkSheet.Cells("A1").LoadFromDataTable(myTestdt, true);

        var formatRange = xlWorkSheet.Cells(1, 1, 1, myTestdt.Columns.Count);

        formatRange.Style.Font.Bold = true;
        formatRange.Style.Fill.PatternType = Style.ExcelFillStyle.Solid;
        formatRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#CDFFCC"));
        formatRange.Style.Font.Size = 10;
        formatRange.Style.Font.Name = "Arial";
        formatRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
        formatRange.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
        formatRange.Style.WrapText = true;

        formatRange.AutoFilter = true;

        for (int index = 0; index <= myTestdt.Columns.Count - 1; index++)
        {
            if (myTestdt.Columns(index).DataType.Name == "DateTime")
            {
                formatRange = xlWorkSheet.Cells(2, index + 1, myTestdt.Rows.Count, index + 1);
                formatRange.Style.Numberformat.Format = "dd/mm/yyyy";
            }
        }

        xlWorkSheet.View.FreezePanes(2, 2);

        xlWorkSheet.Cells.AutoFitColumns();

        MyExcel.SaveAs(NewFile);
    }
}

2 个答案:

答案 0 :(得分:0)

我遇到了几乎相同的问题,这确实为我解决了这个问题:

var dictionaryitems = ["computer":"something to make work easy","pen":"used for writing something"] if let index = dictionaryitems.index(forKey: "pen") { print(dictionaryitems[index].key, ":", dictionaryitems[index].value) }

这会在需要时自动将列调整为更小和更宽。

答案 1 :(得分:-1)

这是我用来从DataSet创建Excel的简单类。

请注意我故意避免捕获异常,因为我在调用者中执行此操作。

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ds2Xlsx
{

    public class Ds2ExcelEngine
    {

        public static void CreateExcel(
            DataSet ds,
            string path,
            OfficeOpenXml.Table.TableStyles tableStyle = OfficeOpenXml.Table.TableStyles.Light9,
            bool autofitColumns = true)
        {
            if (ds != null)
            {
                using (ExcelPackage ep = new ExcelPackage())
                {
                    foreach (DataTable dt in ds.Tables)
                    {
                        AddTableWorksheet(tableStyle, autofitColumns, ep, dt);
                    }
                    ep.SaveAs(new System.IO.FileInfo(path));
                }
            }
        }

        private static void AddTableWorksheet(OfficeOpenXml.Table.TableStyles tableStyle, bool autofitColumns, ExcelPackage ep, DataTable dt)
        {
            ExcelWorksheet ew = ep.Workbook.Worksheets.Add(dt.TableName);
            int row = 1;
            int column = 1;
            foreach (DataColumn dc in dt.Columns)
            {
                ew.Cells[row, column].Value = dc.Caption;
                column++;
            }

            foreach (DataRow dr in dt.Rows)
            {
                column = 1;
                row++;
                foreach (DataColumn dc in dt.Columns)
                {
                    ew.Cells[row, column].Value = dr[dc];
                    column++;
                }
            }

            column = 1;
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.DataType == typeof(DateTime))
                {
                    ew.Cells[1, column, row, column].Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
                }
                column++;
            }

            var excelTable = ew.Tables.Add(new ExcelAddressBase(1, 1, row, column - 1), $"tbl_{ dt.TableName }");
            excelTable.TableStyle = tableStyle;
            if (autofitColumns)
            {
                ew.Cells[ew.Dimension.Address].AutoFitColumns();
            }
        }
    }

}

当我打开我创建的Excel时,所有列都会正确显示,无论是标题还是内容。