[英]How to set “AutoSize” to Excel sheet column? (NPOI)
根據如何在使用NPOI創建的Excel文檔中將列設置為“自動調整大小”? 我這樣做了:
foreach (DataColumn column in dataTable.Columns)
{
int rowIndex = 0;
foreach (DataRow row in dataTable.Rows)
{
HSSFRow dataRow = sheet.CreateRow(rowIndex);
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
rowIndex++;
}
sheet.AutoSizeColumn(column.Ordinal);
}
但它不起作用。 怎么做對嗎?
以下是一些使用循環的代碼:
HSSFWorkbook spreadsheet = new HSSFWorkbook();
DataSet results = GetSalesDataFromDatabase();
//here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
HSSFSheet sheet1 = spreadsheet.CreateSheet("Sheet1");
foreach (DataColumn column in results.Tables[0].Columns)
{
int rowIndex = 0;
foreach (DataRow row in results.Tables[0].Rows)
{
HSSFRow dataRow = sheet1.CreateRow(rowIndex);
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
rowIndex++;
}
sheet1.AutoSizeColumn(column.Ordinal);
}
//Write the stream data of workbook to the file 'test.xls' in the temporary directory
FileStream file = new FileStream(Path.Combine(Path.GetTempPath(), "test.xls") , FileMode.Create);
spreadsheet.Write(file);
file.Close();
如果它對您不起作用,那么我們需要查看您要推出的數據類型,看看是否存在差異,從而產生差異。 (我假設我們沒有版本差異或類似的東西)。
只是為了通過YellowFog添加額外的答案。 我發現我必須將所有數據添加到工作表中,然后遍歷列,設置AutoSizeColumn(idx)以使其正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.