我有这个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();
Run Code Online (Sandbox Code Playgroud)
sheet.Columns["D:D"].ColumnWidth = 17.57;
Run Code Online (Sandbox Code Playgroud)
要么
sheet.Columns[1].ColumnWidth = 17.57;
Run Code Online (Sandbox Code Playgroud)
您可以在Excel中记录宏,然后查看生成的代码(对象模型是相同的).