使用 EPPLus 库,我试图以这种方式在 xlsx 单元格中自动调整非常长的字符串:
worksheet.Cells.AutoFitColumns();
行数:1000
列数:10
对于 2 列,我希望每个单元格中包含大约 6000 个字符。 在这种情况下,AutoFitColumns 方法会生成以下异常:
Message: A generic error occurred in GDI+.
StackTrace: at System.Drawing.Graphics.MeasureString(String text, Font font, SizeF layoutArea, StringFormat stringFormat) at System.Drawing.Graphics.MeasureString(String text, Font font, Int32 width, StringFormat format) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth, Double MaximumWidth) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns()...
编辑
这是我的完整代码:
using (ExcelPackage package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Setup the first row with headers
for (int j = 0; j < fields.Length; j++)
{
worksheet.Cells[1, j + 1].Value = fields[j];
}
Color colFromHex = ColorTranslator.FromHtml("#B4B4B4");
worksheet.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Row(1).Style.Fill.BackgroundColor.SetColor(colFromHex);
// Insert new rows
for (int i = 0; i < elements.Count; i++)
{
// this will return List<object>
var properties = elements[i].GetPatentProperties();
for (int j = 0; j < properties.Count; j++)
{
worksheet.Cells[i + 2, j + 1].Value = properties[j];
}
}
// This will throw an exception for big number of elements: ~ 1000 element
worksheet.Cells.AutoFitColumns();
worksheet.Cells.Style.WrapText = true;
//worksheet.Cells[autosize].Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous;
package.Save();
}
请注意,对于相同的元素列表,如果我删除 worksheet.Cells.AutoFitColumns();
,我将无一异常(exception)地得到我的 xlsx 文件。
是否有可能克服这个问题?
最佳答案
您是否尝试过设置最小和最大列尺寸?
ws.Cells.AutoFitColumns(10, 60);
关于c# - 使用 EPPLus 自动调整长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44687723/