【发布时间】:2020-06-12 12:48:49
【问题描述】:
我想制作一个 Excel 表格,其中包含一些列(具有不同的字体/字体大小),然后在不启动 Excel 或保存文件的情况下获取列的大小(自动适合)。
举个例子: example
我希望能够在无需启动 Excel 或从 C# 保存工作表的情况下获得此信息,我希望它在代码中的内存中。这可能吗?
谢谢。
【问题讨论】:
标签: c# .net excel windows winforms
我想制作一个 Excel 表格,其中包含一些列(具有不同的字体/字体大小),然后在不启动 Excel 或保存文件的情况下获取列的大小(自动适合)。
举个例子: example
我希望能够在无需启动 Excel 或从 C# 保存工作表的情况下获得此信息,我希望它在代码中的内存中。这可能吗?
谢谢。
【问题讨论】:
标签: c# .net excel windows winforms
您可以使用名为 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();
【讨论】: