【问题标题】:Make a column in Excel and get its auto width without starting Excel / saving the file在 Excel 中创建一列并在不启动 Excel/保存文件的情况下获取其自动宽度
【发布时间】:2020-06-12 12:48:49
【问题描述】:

我想制作一个 Excel 表格,其中包含一些列(具有不同的字体/字体大小),然后在不启动 Excel 或保存文件的情况下获取列的大小(自动适合)。

举个例子: example

我希望能够在无需启动 Excel 或从 C# 保存工作表的情况下获得此信息,我希望它在代码中的内存中。这可能吗?

谢谢。

【问题讨论】:

    标签: c# .net excel windows winforms


    【解决方案1】:

    您可以使用名为 EPPlus 的 Nuget 包来执行此操作。也可能使用 Excel Interop,但我更喜欢使用这个包,因为它不依赖于安装的 Excel。

    你可以像这样建立一个电子表格。

    ExcelPackage excel = new ExcelPackage(); //Has constructors that accept file path as string or Stream.
    
    //For demo purposes create a dummy spreadsheet.
    var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
    //Set a cell value
    worksheet.Cells["A1"].Value = "This is some sample text...";
    //Make the font bold
    worksheet.Cells["A1"].Style.Font.Bold = true;
    //Autofit all the columns
    worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
    
    //Get the column width. This is not 0 based.
    //You can then round this to 2 decimal places if you want to
    double colAWidth = worksheet.Column(1).Width;
    

    这有帮助吗?这就是你所追求的吗?

    根据我们的 cmets,您可以使用 Excel 互操作来获得 Excel 显示的确切宽度,但这有其自身的缺点,例如不支持流,因此您需要相应地保存和删除任何文件。

    var xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlApp.Workbooks.Open(@"C:\MySpreadsheet.xlsx");
    
    var sheet = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.ActiveWorkbook.ActiveSheet;
    var columnRange = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[1, 1];
    var colWidth = (double)columnRange.ColumnWidth;
    xlApp.Quit();
    

    【讨论】:

    • 向 MVP 致敬!你知道如何更改字体/字体大小/使其变为粗体(因为它将是不同的宽度)再次感谢。
    • 我刚刚测试了这个,它没有给出准确的宽度?
    • 我已经更新了我的答案,包括将字体加粗。但是是的,我似乎在 Excel 中也看到了非常不同的结果。嗯。
    • 看起来这是有正当理由的。在 GitHub 上查看此问题 github.com/JanKallman/EPPlus/issues/89
    • 所以我对此无能为力?我必须使用互操作吗?
    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多