.net c# excel 列自动调整
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1345396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.net c# excel column AutoFit
提问by
I'm working with an excel object in c#. I want to auto-fit the columns, but like this: I want the columns' width to be 5 bigger than what the AutoFit method set.
我正在使用 c# 中的 excel 对象。我想自动调整列,但像这样:我希望列的宽度比 AutoFit 方法设置的宽度大 5。
How can I get the width after AutoFit() is used?
使用 AutoFit() 后如何获取宽度?
How can I make the columns 5 bigger than this width?
如何使第 5 列大于此宽度?
回答by shahkalpesh
Assuming that you are on cell A1 & have long text in it, following code will make the column Autofit and then increase the width by 5 characters.
假设您在单元格 A1 上并在其中包含长文本,以下代码将使列自动调整,然后将宽度增加 5 个字符。
Selection.Columns.Autofit
Selection.Columns(1).ColumnWidth = Selection.Columns(1).ColumnWidth + 5
回答by Mike Rosenblum
If you wish to use the Selection object and have IntelliSense with early binding, you need to cast the Selection object to a Range first:
如果您希望使用 Selection 对象并让 IntelliSense 具有早期绑定,则需要先将 Selection 对象强制转换为 Range:
Excel.Range selectedRange = (Excel.Range)myExcelApp.Selection;
selectedRange.Columns.AutoFit();
foreach (Excel.Range column in selectedRange.Columns)
{
column.ColumnWidth = (double)column.ColumnWidth + 5;
}
-- Mike
——迈克
回答by Celso Jr
Try to loop through your rows to get the text length of it:
尝试遍历您的行以获取其文本长度:
var row = 1;
ws.Column(1).AutoFit(ws.Cells[row, 1].Text.Length + 5);
Where wsis your Worksheet:
ws在哪里是您的工作表:
var pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Plan1")
回答by Karthikeyan P
Try Like this,
试试这样,
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(data_table, true);
//Set full Sheet Auto Fit
ws.Cells[1, 1, data_table.Rows.Count, data_table.Columns.Count].AutoFitColumns();