您的位置:首页 > 编程语言 > C#

在C#中调用Excel

2010-01-20 17:13 148 查看
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;

------------------------

特别是第二点。好有用!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐