在C#生成的Excel工作表中自动调整列宽

时间:2015-08-07 16:00:25

标签: c# excel office-interop

我正在尝试通过使用C#从SQL Server数据库导出数据来自动生成Excel表格中的列和行。我做了一些研究,我发现的解决方案似乎没有任何影响。

//This code produces the correct Excel File with the expected content
Excel.Application ExcelApp = new Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
for (int i = 1; i < myDataTable.Rows.Count + 2; i++)
{
   for (int j = 1; j < myDataTable.Columns.Count + 1; j++)
   {
      if (i == 1)
      {
         ExcelApp.Cells[i, j] = myColumnCollection[j - 1].ToString();
      }
      else
         ExcelApp.Cells[i, j] = myDataTable.Rows[i - 2][j - 1].ToString();
   }
}
ExcelApp.ActiveWorkbook.SaveCopyAs(Application.StartupPath + "\\test.xlsx");
ExcelApp.ActiveWorkbook.Saved = true;

//This code is where I tried to do the Autofit work
Excel.Worksheet ws = ExcelApp.ActiveWorkbook.Worksheets[1];
Excel.Range range = ws.UsedRange; 
//ws.Columns.ClearFormats();
//ws.Rows.ClearFormats();
//range.EntireColumn.AutoFit();
//range.EntireRow.AutoFit();
ws.Columns.AutoFit();
ws.Rows.AutoFit();

ExcelApp.Quit();

我已经尝试了几种方法。我想我理解Range.Columns.Autofit()Range.EntireColumn.AutoFit()之间的区别,并且在获得Worksheet.Columns.ClearFormat()之后尝试在AND之前使用UsedRange。据我所知,这些都没有影响我的档案。

我需要做些什么才能将列和行自动调整到其内容中?

1 个答案:

答案 0 :(得分:0)

感谢Derek指出显而易见的事实。我完成修改后需要保存工作簿。我只需将我的Autofit()内容移到保存之上。

 Excel.Worksheet ws = ExcelApp.ActiveWorkbook.Worksheets[1];
        ws.Columns.AutoFit();
        ws.Rows.AutoFit();
        ExcelApp.ActiveWorkbook.SaveCopyAs(Application.StartupPath + "\\HaulerInfo.xlsx");
        ExcelApp.ActiveWorkbook.Saved = true;