如何设置以编程方式创建的 xlsx 文件中单元格的宽度?
我有这段 C# 代码,可将数据集转换为 xlsx。有没有办法设置创建的 xlsx 文件的工作表的单元格或列宽?
//Get the filename
String filepath = args[0].ToString();
//Convert the file to dataset
DataSet ds = Convert(filepath.ToString(), "tblCustomers", "\t");
//Create the excell object
Excel.Application excel = new Excel.Application();
//Create the workbook
Excel.Workbook workBook = excel.Workbooks.Add();
//Set the active sheet
Excel.Worksheet sheet = workBook.ActiveSheet;
int i = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int j = 0; j < row.ItemArray.Length; j++)
{
sheet.Cells[i + 1, j + 1] = row[j];
}
i++;
}
workBook.SaveAs(@"C:\fromCsv.xlsx");
workBook.Close();
I have this C# code which converts a dataset to xlsx. Is there a way to set the cell or column width of the sheet of the xlsx file created?
//Get the filename
String filepath = args[0].ToString();
//Convert the file to dataset
DataSet ds = Convert(filepath.ToString(), "tblCustomers", "\t");
//Create the excell object
Excel.Application excel = new Excel.Application();
//Create the workbook
Excel.Workbook workBook = excel.Workbooks.Add();
//Set the active sheet
Excel.Worksheet sheet = workBook.ActiveSheet;
int i = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int j = 0; j < row.ItemArray.Length; j++)
{
sheet.Cells[i + 1, j + 1] = row[j];
}
i++;
}
workBook.SaveAs(@"C:\fromCsv.xlsx");
workBook.Close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者
您可以在 Excel 中记录宏,然后查看生成的代码(对象模型相同)。
or
You can record Macros in Excel and then look to generated code (object model is the same).
要将所有列宽度自动设置为其内容的“正确大小”,您可以通过调用 AutoFit 来解决此问题,如下所示:
但是,有时列中的一两个“恶意”值会使该列变得超宽,您必须将列拖到左侧才能看到更多数据。您可以通过使用自动调整,然后指定任何有问题的列的宽度来克服此第 22 条规则。下面是如何做到这一点的代码,它假设第 1 列是要控制的列,42 是您希望它采用的宽度:
注意:作为一个额外的好处,您可以将超长的内容换行(尤其是如果它们位于合并(多行)范围内,则很有用),如下所示(其中“范围”是您在填充列时定义的范围):
注意:您需要为此代码添加 Microsoft.Offie.Interop.Excel 程序集去工作。
To automaticaly set all column widths to "right-size" for their contents, you can take care of this by calling AutoFit, like so:
However, sometimes one or two "rogue" values in a column make that column go ultra-wide, and you have to drag the column way over to the left so as to see more of the data. You can overcome this Catch-22 by using both AutoFit and then, afterwards, specifying the width of any problematic columns. Here's the code for how to do that, which assumes column 1 is the one to be reined in, and 42 is the width you want it to assume:
Note: As an added nicety, you can have the over-long content wrap (especially useful if they are in a Merged (multi-row) range) like so (where "range" is the Range you defined when populating the column):
Note: You need to add the Microsoft.Offie.Interop.Excel assembly for this code to work.