2

我的 sqldatareader 正在返回约 200 行数据。这些行中大约有一半有一列包含整个 xml 文档。我假设此列导致 autofit() 方法挂起。我怎样才能让它要么抛出异常,要么成功完成。我不在乎哪一个,我只需要这个[自动化]程序来完成。

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

1 回答 1

2

除了我上面的评论,我正在使用我几天前创建的这个特定的示例文件,其中有 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

截图

在此处输入图像描述

您的程序需要更多时间,因为有 200 行,并且每个 Excel 单元格中的数据可能比我的要多。

那么解决方案是什么?

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

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

        Rng.EntireColumn.ColumnWidth = 254;

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

于 2013-04-05T20:13:28.740 回答