4

我在使用 Interop 在 Excel 2003 中复制工作表时遇到问题。该代码适用于 30-40 个副本,然后抛出异常“HRESULT 异常:0x800A03EC”。以下测试代码已包含http://support.microsoft.com/kb/210684/en-us中建议的补丁,但没有成功。有谁知道任何解决方法?提前致谢

using Excel = Microsoft.Office.Interop.Excel;

private void button2_Click(object sender, EventArgs e)
    {
        string template_path = @"c:\temp\template.xlt";
        string filename = @"c:\temp\testxl1.xls";
        if (File.Exists(filename))
            File.Delete(filename);

        object missing = System.Reflection.Missing.Value;

        System.Globalization.CultureInfo my_culture = System.Threading.Thread.CurrentThread.CurrentCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

        Excel.ApplicationClass xlapp = new Excel.ApplicationClass();
        xlapp.Visible = true;
        xlapp.UserControl = true;

        Excel.Workbook xlwb = xlapp.Workbooks.Add(template_path);

        xlwb.SaveAs(@filename,
            missing, missing, missing, missing, missing,
            Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);


        Excel.Worksheet xlws = xlwb.Worksheets["diario"] as Excel.Worksheet;

        int copies = 200;

        for (int i = 0; i < copies; i++)
        {
            #region Patch kb/210684

            if (copies % 10 == 0)
            {                    
                xlwb.Close(true, missing, missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlwb);
                xlwb = null;

                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlws);
                xlws = null;

                Application.DoEvents();

                xlwb = xlapp.Workbooks.Open(@filename, 0,
                    missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                xlws = xlwb.Worksheets["diario"] as Excel.Worksheet;

            }

            #endregion

            xlws.Copy(System.Reflection.Missing.Value, xlwb.Worksheets.Count);
        }

        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlws);
        xlws = null;

        xlwb.Close(true, missing, missing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlwb);
        xlwb = null;

        xlapp.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlapp);
        xlapp = null;

        System.Threading.Thread.CurrentThread.CurrentCulture = my_culture;
    }
4

1 回答 1

1

我唯一能找到的是,当本地计算机未设置为美国英语时,异常可能是 Excel LCID 问题。

http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

或者

http://support.microsoft.com/kb/320369/en-us

于 2012-10-25T18:25:48.047 回答