簡體   English   中英

如何設置以編程方式創建的xlsx文件中的單元格寬度?

[英]How to set the width of the cell in the xlsx file created programmatically?

我有這個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();
sheet.Columns["D:D"].ColumnWidth = 17.57;

要么

sheet.Columns[1].ColumnWidth = 17.57;

您可以在Excel中記錄宏,然后查看生成的代碼(對象模型是相同的)。

要自動將所有列寬設置為其內容的“正確大小”,您可以通過調用AutoFit來處理此問題,如下所示:

_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”是您在填充列時定義的范圍):

range.WrapText = true;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM