当前位置:编程文档 >> C# >> 在C#中调用Excel
首页

在C#中调用Excel

所属类别:C#
推荐指数:★★★
文档人气:394
本周人气:23
发布日期:2008-5-24

1. 调用Excel的COM组件
    在项目中打开Add Reference对话框,选择COM栏,之后在COM列表中找到"Microsoft Excel 11.0 Object Library"(Office 2003),然后将其加入到项目的References中即可。Visual C#.NET会自动产生相应的.NET组件文件,以后即可正常使用。

2. 打开Excel表格
    Excel.Application excel = new Excel.Application(); //引用Excel对象
    Excel.Workbook book = excel.Application.Workbooks.Add(Missing.Value); //引用Excel工作簿
    excel.Visible = bVisible; //使Excel可视

有时调用excel.Application.Workbooks.Add(Missing.Value)会遇到如下错误:
    Exception:
        Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
这是Excel自身的一个bug,当本地系统环境被设置成非英文的,而Excel是英文的时候,就会出现,需要临时设定英文环境,代码如下:
    System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

3. 往Excel表格中插入数据
    Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets["Sheet1"]; // 选中当前新建Sheet(一般为Sheet1)
有两种插入方法
a. 逐格插入数据
    sheet.Cells[iRow, iCol] = value; // 左上角第一格的坐标是[1, 1]
b. 按块插入数据
    object[,] objVal = new object[Height, Length];
    // 设置数据块
    Excel.Range range = sheet.get_Range(sheet.Cells[iRow, iCol], sheet.Cells[iRow + Height, iCol + Length])
    range.Value2 = objVal;

4. 清理内存和恢复环境

    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
    while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excel) > 0) ;
    range = null;
    sheet = null;
    book = null;
    excel = null;
    GC.Collect();
    System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;

文档说明:

     

相关文档


读取评论列表……