使用 C# windowsforms 应用程序导出 Microsoft Excel 中的数据

发布于 2024-08-24 14:32:37 字数 1275 浏览 5 评论 0原文

当我尝试将数据导出到 Excel 时出现异常...异常是

COMException:HRESULT 异常:0x800A03EC。

我该如何解决这个错误?我该如何得到解决方案?告诉我这个问题的解决方案...

提前致谢...

我的代码是:

         {
        oxl = new Excel.Application();
        oxl.Visible = true;
        oxl.DisplayAlerts = false;


        wbook = oxl.Workbooks.Add(Missing.Value);

        wsheet = (Excel.Worksheet)wbook.ActiveSheet;
        wsheet.Name = "Customers"; 



        DataTable dt = InstituteTypeDetail();

        int rowCount = 1;
        foreach (DataRow dr in dt.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < dt.Columns.Count + 1; i++)
            {
                // Add the header the first time through
                if (rowCount == 2)
                {
                    wsheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                }
                wsheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        range = wsheet.get_Range(wsheet.Cells[1, 1],
                      wsheet.Cells[rowCount, dt.Columns.Count]);//In this place i got the exception
        range.EntireColumn.AutoFit();


        wsheet = null;
        range = null;

}

我做错了什么?解决这个异常的方法是什么....有人请告诉我...

i got the exception when i am trying to export data to excel.... the exception is

COMException: Exception from HRESULT: 0x800A03EC.

How shall i solve this error? How shall i get solution? Tell me the solution of this problem...

Thanks in advance...

My Code is:

         {
        oxl = new Excel.Application();
        oxl.Visible = true;
        oxl.DisplayAlerts = false;


        wbook = oxl.Workbooks.Add(Missing.Value);

        wsheet = (Excel.Worksheet)wbook.ActiveSheet;
        wsheet.Name = "Customers"; 



        DataTable dt = InstituteTypeDetail();

        int rowCount = 1;
        foreach (DataRow dr in dt.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < dt.Columns.Count + 1; i++)
            {
                // Add the header the first time through
                if (rowCount == 2)
                {
                    wsheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                }
                wsheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        range = wsheet.get_Range(wsheet.Cells[1, 1],
                      wsheet.Cells[rowCount, dt.Columns.Count]);//In this place i got the exception
        range.EntireColumn.AutoFit();


        wsheet = null;
        range = null;

}

what i did wrong? what is the way to solve this exception.... Anyone plz tell me...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

稍尽春風 2024-08-31 14:32:37

以下示例代码对我来说效果很好。你能尝试一下吗?已修改您的示例。最后释放对所有 com 对象的引用始终是一个好习惯。

Application oxl = null;
        try
        {
            oxl = new Application( );
            oxl.Visible = true;
            oxl.DisplayAlerts = false;

            string fileName = @"D:\one.xls";
            object missing = Missing.Value;
            Workbook wbook = oxl.Workbooks.Open( fileName, missing, missing, missing, missing, missing,missing,missing,missing,missing,missing,missing,missing,missing,missing );

            Worksheet wsheet = ( Worksheet )wbook.ActiveSheet;
            wsheet.Name = "Customers";


            System.Data.DataTable dt = new System.Data.DataTable( "test" );
            dt.Columns.Add( "col1" );
            dt.Columns.Add( "col2" );
            dt.Columns.Add( "col3" );

            dt.Rows.Add( new object[ ] { "one", "one", "one" } );
            dt.Rows.Add( new object[ ] { "two", "two", "two" } );
            dt.Rows.Add( new object[ ] { "three", "three", "three" } );


            for ( int i = 1 ; i <=  dt.Columns.Count ; i++ )
            {
                wsheet.Cells[ 1, i ] = dt.Columns[ i - 1 ].ColumnName;
            }

            for ( int j = 1 ; j <= dt.Rows.Count ; j++ )
            {
                for ( int k = 0 ; k <  dt.Columns.Count ; k++ )
                {
                    DataRow dr = dt.Rows[ k ];
                    wsheet.Cells[ j +1, k+1 ] = dr[ k ].ToString( );
                }
            }

            Range range = wsheet.get_Range( wsheet.Cells[ 1, 1 ],
                          wsheet.Cells[ dt.Rows.Count + 1, dt.Columns.Count ] );//In this place i got the exception
            range.EntireColumn.AutoFit( );

            wbook.Save( );

            wsheet = null;
            range = null;


        }
        finally
        {
            oxl.Quit( );
            System.Runtime.InteropServices.Marshal.ReleaseComObject( oxl );
            oxl = null;
        }

The following sample code works fine for me. Can you give it a try. Have modified your sample. Also it is always a good practice to release references to all com objects at the end.

Application oxl = null;
        try
        {
            oxl = new Application( );
            oxl.Visible = true;
            oxl.DisplayAlerts = false;

            string fileName = @"D:\one.xls";
            object missing = Missing.Value;
            Workbook wbook = oxl.Workbooks.Open( fileName, missing, missing, missing, missing, missing,missing,missing,missing,missing,missing,missing,missing,missing,missing );

            Worksheet wsheet = ( Worksheet )wbook.ActiveSheet;
            wsheet.Name = "Customers";


            System.Data.DataTable dt = new System.Data.DataTable( "test" );
            dt.Columns.Add( "col1" );
            dt.Columns.Add( "col2" );
            dt.Columns.Add( "col3" );

            dt.Rows.Add( new object[ ] { "one", "one", "one" } );
            dt.Rows.Add( new object[ ] { "two", "two", "two" } );
            dt.Rows.Add( new object[ ] { "three", "three", "three" } );


            for ( int i = 1 ; i <=  dt.Columns.Count ; i++ )
            {
                wsheet.Cells[ 1, i ] = dt.Columns[ i - 1 ].ColumnName;
            }

            for ( int j = 1 ; j <= dt.Rows.Count ; j++ )
            {
                for ( int k = 0 ; k <  dt.Columns.Count ; k++ )
                {
                    DataRow dr = dt.Rows[ k ];
                    wsheet.Cells[ j +1, k+1 ] = dr[ k ].ToString( );
                }
            }

            Range range = wsheet.get_Range( wsheet.Cells[ 1, 1 ],
                          wsheet.Cells[ dt.Rows.Count + 1, dt.Columns.Count ] );//In this place i got the exception
            range.EntireColumn.AutoFit( );

            wbook.Save( );

            wsheet = null;
            range = null;


        }
        finally
        {
            oxl.Quit( );
            System.Runtime.InteropServices.Marshal.ReleaseComObject( oxl );
            oxl = null;
        }
滥情空心 2024-08-31 14:32:37

当您收到错误时,您的 rowCount 实际上正确吗?您从 1 开始,但随后立即递增 - 因此,当您在 foreach 循环中检查第 1 行时,rowCount 实际上是 2。

我认为您的 < code>rowCount 应初始化为 0(零)。然后您的标题行检查应查找 if (rowCount == 1)

Is your rowCount actually correct at the point you get the error? You're starting it from 1, but then incrementing it immediately - so when you're examining row 1 in your foreach loop, rowCount is actually 2.

I think your rowCount should be initialised to 0 (zero.) Then your header row check should look for if (rowCount == 1).

岁月染过的梦 2024-08-31 14:32:37

get_Range 期望单元格名称为字符串,即“A1”、“B25”等。您可以尝试用以下代码替换该行:

range = wsheet.Cells(1, 1);
range = range.Resize(rowCount, dt.Columns.Count);

get_Range expects the name of a cell as string, i.e. something like "A1", "B25" etc. You could try to replace the line with the following code:

range = wsheet.Cells(1, 1);
range = range.Resize(rowCount, dt.Columns.Count);
熟人话多 2024-08-31 14:32:37

SpreadsheetGear for .NET 可让您通过 .NET 处理 Excel 工作簿,而不会出现与 Excel COM Interop 相关的问题。 SpreadsheetGear 也比 COM Interop 更快 - 特别是当像代码那样循环访问多个单元格时。

以下是一些与使用 SpreadsheetGear API 的代码执行相同操作的代码:

using System;
using SpreadsheetGear;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"D:\one.xls";
            IWorkbook wbook = SpreadsheetGear.Factory.GetWorkbook(fileName);
            IWorksheet wsheet = wbook.ActiveWorksheet;
            wsheet.Name = "Customers";
            System.Data.DataTable dt = new System.Data.DataTable("test");
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Columns.Add("col3");
            dt.Rows.Add(new object[] { "one", "one", "one" });
            dt.Rows.Add(new object[] { "two", "two", "two" });
            dt.Rows.Add(new object[] { "three", "three", "three" });
            wsheet.Cells[0, 0, dt.Rows.Count - 1, dt.Columns.Count - 1].CopyFromDataTable(dt, SpreadsheetGear.Data.SetDataFlags.None);
            wsheet.UsedRange.EntireColumn.AutoFit();
            wbook.Save();
        }
    }
}

您可以在 此处查看实时示例 如果您想亲自尝试,请在此处下载免费试用版。

免责声明:我拥有 SpreadsheetGear LLC

SpreadsheetGear for .NET will let you work with Excel workbooks from .NET without the problems associated with Excel COM Interop. SpreadsheetGear is also faster than COM Interop - especially when looping through a number of cells as your code seems to do.

Here is some code which does the same thing as your code using the SpreadsheetGear API:

using System;
using SpreadsheetGear;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"D:\one.xls";
            IWorkbook wbook = SpreadsheetGear.Factory.GetWorkbook(fileName);
            IWorksheet wsheet = wbook.ActiveWorksheet;
            wsheet.Name = "Customers";
            System.Data.DataTable dt = new System.Data.DataTable("test");
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Columns.Add("col3");
            dt.Rows.Add(new object[] { "one", "one", "one" });
            dt.Rows.Add(new object[] { "two", "two", "two" });
            dt.Rows.Add(new object[] { "three", "three", "three" });
            wsheet.Cells[0, 0, dt.Rows.Count - 1, dt.Columns.Count - 1].CopyFromDataTable(dt, SpreadsheetGear.Data.SetDataFlags.None);
            wsheet.UsedRange.EntireColumn.AutoFit();
            wbook.Save();
        }
    }
}

You can see live samples here and download the free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文