ClosedXML 如何设置整个工作簿的单元格宽度?

ClosedXML how to set cell width for whole workbook?

我正在使用 closedXml 将数据导出到 Excel。但是我的列需要根据内容进行调整,因此我尝试手动指定列宽:

var ws = workbook.Worksheets.Add("Column Settings");

col.Width = 50;

对 me.I 无效也尝试过:

Columns().AdjustToContents();

但是也没有结果。因此,寻找一种可以在整个 sheet 或工作簿中预先设置单元格宽度的解决方案。 这是我的代码:

    //variables 
    XLWorkbook workbook = new XLWorkbook();
    var wsDep = workbook.Worksheets.Add("MBR");
    wsDep.Columns().AdjustToContents();
    DataTable dt = new DataTable() { TableName = "MBR" };
    DataSet ds = new DataSet();
    TagRepo tr = new TagRepo();
    List<string> tags = new List<string>();
    tags.Add("TimeStamp");

    //list min,max,avg.
    foreach (var item in tr.getAllTagNames())
    { 
        tags.Add(item.Trim()+"_Min");
        tags.Add(item.Trim() + "_Max");
        tags.Add(item.Trim() + "_Avg");
    }
    //input data
    int l = tags.Count();
    //Colum names
    string[] columns = new string [l];

    for (int i = 0; i < l; i++)
    {
        columns[i] = tags[i];
    }
    var rows = new object[][]
    {
    new object[] {"1", 2, false },
    new object[] { "test", 10000, 19.9 },
    };
    //Add columns
    dt.Columns.AddRange(columns.Select(c => new DataColumn(c.ToString())).ToArray());
    //Add rows
    foreach (var row in rows)
    {
        dt.Rows.Add(row);
    }

    //Convert datatable to dataset and add it to the workbook as worksheet
    ds.Tables.Add(dt);
    workbook.Worksheets.Add(ds);
    
    //save
    //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    string savePath = Path.Combine(@"\nas\TreviMap\Pilootproeven en opvolging-IC\Export data", "toon.xlsx");
    workbook.SaveAs(savePath, false);

您需要在填写工作表后致电 Columns().AdjustToContents();