简体   繁体   English

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

[英]Autofit Column Width in C#-generated Excel sheet

I'm trying to Autofit the columns and rows in an Excel sheet that I make by exporting data from a SQL Server database, using C#. 我正在尝试通过使用C#从SQL Server数据库导出数据来自动拟合我制作的Excel工作表中的列和行。 I've done a bit of research, and the solutions I've found don't seem to have any affect. 我做了一些研究,发现的解决方案似乎没有任何影响。

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

I've tried a few methods near the end. 我已经尝试了几种接近尾声的方法。 I think I understand the difference between Range.Columns.Autofit() and Range.EntireColumn.AutoFit() , and have tried using Worksheet.Columns.ClearFormat() before AND after getting the UsedRange . 我想我了解Range.Columns.Autofit()Range.EntireColumn.AutoFit()之间的区别,并尝试在获取UsedRange之前和之后使用Worksheet.Columns.ClearFormat() None of these have affected my file at all, as far as I can tell. 据我所知,这些都不影响我的文件。

What do I need to do in order to have the columns and rows autofitted to their content? 为了使列和行自动适应其内容,我需要做什么?

Thanks goes to Derek for pointing out the obvious. 感谢Derek指出显而易见的内容。 I needed to save the Workbook after I was done modifying it. 完成修改后,我需要保存工作簿。 I just had to move my Autofit() stuff above the save. 我只需要将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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM