2012-01-31 45 views
2

我有這個C#代碼將數據集轉換爲xlsx。有沒有辦法設置創建的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(); 

回答

7
sheet.Columns["D:D"].ColumnWidth = 17.57; 

sheet.Columns[1].ColumnWidth = 17.57; 

您可以錄製Excel宏,然後看看生成的代碼(對象模型是一樣的)。

+0

是的它是完美的。謝謝 – themis 2012-01-31 13:00:38

1

要automaticaly設置所有列的寬度,以「正確大小」爲自己的內容,可以通過調用自動調整照顧到這一點,就像這樣:

_xlSheet.Columns.AutoFit(); 

然而,有時一個或兩個「流氓」的價值觀在列中使該列超寬,並且必須將列方向拖到左側才能看到更多數據。你可以通過使用AutoFit來克服這個Catch-22,然後,然後指定任何有問題的列的寬度。下面是如何做到這一點的代碼,它假定列1是被勒住的一個,而42是你希望它承擔寬度:

private Worksheet _xlSheet; 
private static readonly int ITEMDESC_COL = 1; 
private static readonly int WIDTH_FOR_ITEM_DESC_COL = 42; 
. . . 
_xlSheet.Columns.AutoFit(); 
// Now take back the wider-than-the-ocean column 
((Range)_xlSheet.Cells[ITEMDESC_COL, ITEMDESC_COL]).EntireColumn.ColumnWidth = WIDTH_FOR_ITEM_DESC_COL; 

注:作爲一個附加的精密,你可以有超長的內容包(如果他們是在合併(多行特別有用)範圍內)像這樣(其中「範圍」是填充柱時,你所定義的範圍):

range.WrapText = true; 

注意:您需要爲此代碼添加Microsoft.Offie.Interop.Excel程序集。

相關問題