Excel._Worksheet.Columns.Autofit()方法被挂起

我的sqldatareader正在返回〜200行数据。 大约有一半的行有一列包含整个xml文档。 我假设这个列导致autofit()方法挂起。 我怎么能得到这个抛出exception,或成功完成。 我不在乎哪一个,我只需要这个[自动]程序来完成。

Excel.Application xl = null; Excel._Workbook wb; Excel._Worksheet ws; try { xl = new Microsoft.Office.Interop.Excel.Application(); xl.Visible = false; while (reader.HasRows && !done) { wb = (Excel._Workbook)(xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet)); ws = (Excel._Worksheet)wb.ActiveSheet; // Insert column headers for (int counter = 0; counter < reader.FieldCount; counter++) ws.Cells[1, counter + 1] = reader.GetName(counter); // Write the data to the excel file while (reader.Read()) { for (int counter = 1; counter <= reader.FieldCount; counter++) { // Need to format this column so excel doesn't change how it looks if (report.ReportName == "RPTAAMVANetBatch" && reader.GetName(counter - 1) == "CorrelationID") ws.Cells[rowCounter, counter] = String.Format("''{0}'", reader.GetValue(counter - 1)); else ws.Cells[rowCounter, counter] = reader.GetValue(counter - 1); } rowCounter++; } RecordsProcessed = rowCounter - 1; // Format the excel file to liking ws.get_Range(ws.Cells[1, 1], ws.Cells[rowCounter - 1, reader.FieldCount]); ws.Columns.AutoFit(); 

除了上面我的评论之外,我使用了前两天创build的这个特定的示例文件,其中有100行,在Col E 栏中,我有几个电子邮件的整个身体( 我已经把一个红色的盒子,以保护身份和电子邮件的内容

在这里输入图像说明

这是一个简单的VBA代码,我运行它来检查自动调整E列所需的时间

 Sub Test() Dim startTime As String Dim endTime As String startTime = Now Columns("E:E").EntireColumn.AutoFit endTime = Now Debug.Print "The process started at " & startTime & " and got over at " & endTime End Sub 

ScreenShot

在这里输入图像描述

你的程序需要更多的时间,因为有200行,也许你有更多的数据在每个Excel单元比我的。

那么解决scheme是什么?

我能想到的最好的解决scheme是在将大量数据写入它之前将列扩大到MAX (254.86)。 像这样的东西

  Excel.Range Rng = ws.get_Range("E:E",System.Type.Missing); Rng.EntireColumn.ColumnWidth = 254; 

注意 :请勿为该列或整个工作表使用Autofit。 如果您确实需要使用Autofit请将其分解。 例如,在我的情况下,我会做自动调整从列1到4,然后从6到最后一列