2011-05-19 25 views
6

根據How can columns be set to 'autosize' in Excel documents created with NPOI?我這樣做:如何將「AutoSize」設置爲Excel工作表列? (NPOI)

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); 
} 

但它不工作。如何做對?

回答

10

下面是一些代碼爲我工作,使用循環:

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(); 

如果它不爲你工作,那麼我們就需要看的數據類型你推出的,見如果有差異,那就會有所不同。 (我假設我們沒有版本差異或類似的東西)。

+0

我從你的回答中看不到問題和解決方案。您添加了不存在於問題中的代碼,但該代碼似乎與autosizing無關。 – buffjape 2017-07-06 16:03:17

+0

是的,這就是示例代碼的一點。因此代碼示例之後的單詞。 – Yellowfog 2017-07-07 13:12:19

+0

具體來說,你解決了什麼問題?哪一行代碼修復了它? – buffjape 2017-07-07 14:08:29

1

只是爲YellowFog添加了一點額外的答案。我發現我必須將所有數據添加到工作表,然後遍歷列,設置AutoSizeColumn(idx)以使其正常工作。

相關問題