1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C#实现excel文件的读取 写入以及异常处理 附源码程序

C#实现excel文件的读取 写入以及异常处理 附源码程序

时间:2022-10-09 09:47:36

相关推荐

C#实现excel文件的读取 写入以及异常处理 附源码程序

C#实现excel文件的读取与写入,附源码程序

说明关键代码段源程序下载地址注意事项及异常解决

说明

通过OleDB方式,对execl文件进行读取、写入操作。注:网上很多类似的代码,但是代码中出现很多错误,本文将其中的错误进行了修改,经过测试是可以实现对execl文件读取与写入操作。

关键代码段

1)需要在C#中添加引用——Microsoft.Office.Interop.Excel.dll

注:该步骤在该方法中不需要

如下图所示:

2)添加了 resloveExcel类

using System;using System.Collections.Generic;using System.Data.OleDb;using System.Data;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Diagnostics;using Microsoft.Office.Interop.Excel;namespace testExcel{internal class resolveExcel{//通过OleDB方式public DataSet ExcelToDS(string Path) {string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\"";OleDbConnection conn = new OleDbConnection(strConn);conn.Open(); string strExcel = "";OleDbDataAdapter myCommand = null;DataSet ds = null;strExcel = "select * from [sheet1$]";myCommand = new OleDbDataAdapter(strExcel, strConn);ds = new DataSet();myCommand.Fill(ds, "table1");conn.Close();return ds;}public bool DSToExcel(string Path, DataSet oldds){bool res = true;string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0; HDR=No; IMEX=0'";OleDbConnection myConn = new OleDbConnection(strCon);string strCom = "select * from [Sheet1$]";try{myConn.Open();OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);System.Data.OleDb.OleDbCommandBuilder builder = new OleDbCommandBuilder(myCommand);builder.QuotePrefix = "["; builder.QuoteSuffix = "]"; DataSet newds = new DataSet();myCommand.Fill(newds, "table1");for (int i = 0; i < oldds.Tables[0].Rows.Count; i++){DataRow nrow = newds.Tables["table1"].NewRow();for (int j = 0; j < oldds.Tables[0].Columns.Count; j++){nrow[j] = oldds.Tables[0].Rows[i][j];}newds.Tables["Table1"].Rows.Add(nrow);}myCommand.Update(newds, "table1");myConn.Close();}catch (Exception ex){res = false;throw ex;}return res;}}}

源程序下载地址

源码下载

注意事项及异常解决

1)如该语句myCommand.Update(newds, “table1”);抛出异常-操作必须使用一个可更新的查询,请检查string strCon中的IMEX的值是否为0。

2)如语句conn.Open();抛出System.Data.OleDb.OleDbException:“外部表不是预期的格式。”检查是否打开了该文件,是需要用excel打开该文件,才能操作。

3)该方法需要将需要操作的excel文件用excel打开,才能保证操作成功!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。