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打开,才能保证操作成功!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值