使用C#写WPS的excel

来源:互联网 发布:简谱软件免费下载 编辑:程序博客网 时间:2024/05/22 04:51
使用C#写WPS的excel转自网络

最近因为工作需要,用C#WPS重写excel表的某写数据。因为完全没接触过这方面的内容,所以写起来比较费劲非常简单的一个功能,折腾了多半天。

现在将小白操作记录下来。以备以后查看。

1. 首先将wps的相关COM组件添加至引用。project -> add reference -> com-> Kingsoft ET 2.0 Object Library.

2. 代码中添加using KSO; using ET;

3. 打开xls文件的相关代码:

ET.Application etApp;
ET.workbook etbook;
ET.Worksheet etsheet ;
ET.Range etrange;
//获取工作表表格
etApp = new ET.Application();
etbook = (ET.workbook)etApp.Workbooks.Open(@"c:\file.xls");

//获取数据区域
etsheet = (ET.Worksheet)etbook.Worksheets.get_Item(1);

//获取数据区域 
etrange = (ET.Range)etsheet.UsedRange;

4. 读取某单元格的数据内容:

string strData = ((ET.Range)etrange.get_Item(i, j)).Text;

5. 写入某单元格的数据内容:

((ET.Range)etrange.get_Item(i, j)).Value = strData;

6. 关闭文件及相关资源:

etbook.Close();
etApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(etrange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(etsheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(etbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(etApp);

0 0
原创粉丝点击