以OleDb方式操作Excel文件

Excel可作为一种数据共享的方式交给办公人员,比access要简单方便

Excel可作为OleDb的对象进行操作,这里以03版的Excel为例:

首先要引入以下函数库,并定义必要的对象:

using System.Data;
using System.Data.OleDb;
using System.IO;

  OleDbConnection objConnection;
  OleDbCommand objCommand;
  OleDbDataAdapter objDataAdapter;

  public DataSet objDataSet=new DataSet();

1、创建xls文档

     //生成03版的xls,filepath为文档的路径,sqlCreateTable为创建表的sql语句
public void CreateAXls(string filePath,string sqlCreateTable)
{
try
{
         if (!File.Exists(filePath))
         {
objConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
+ filePath + "; Extended Properties=Excel 8.0;");
string strSql = sqlCreateTable;
objCommand = new OleDbCommand(strSql, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();

objConnection.Close();
         }
}
catch
{ }

}


2、读取工作薄

public void ReadSheet(string path,string tableName)
{
try
{
if ((path.Substring(path.Length - 4, 4) == "xlsx") || (path.Substring(path.Length - 4, 4) == "XLSX"))
{
objConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source="
+ path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1'");
}
else
{
objConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
+ path + "; Extended Properties='Excel 8.0;HDR=YES;IMEX=1'");
}
objConnection.Open();

objDataAdapter = new OleDbDataAdapter("select * from [sheet1$]", objConnection);
objDataAdapter.Fill(objDataSet, tableName);

objConnection.Close();
}
catch
{ }
}

3、插入数据

public void InsertData(string filePath, string sqlInsertData)
{
try
{
objConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
+ filePath + "; Extended Properties=Excel 8.0;");
string strSql = sqlInsertData;
objCommand = new OleDbCommand(strSql, objConnection);
objCommand.CommandText = strSql;
objCommand.CommandType = CommandType.Text;
objConnection.Open();
objCommand.ExecuteNonQuery();

objConnection.Close();
}
catch
{ }
}

插入数据时,最好将所需插入的sql语句串成一个大字串,打开链接一次写入,这样不仅速度快,同时能减少IO错误




原文地址:https://www.cnblogs.com/lingcoln/p/2305852.html