解析excel表格为DataSet

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using Log;
namespace Common
{
public class ExcelInputHelper
{
public static ExcelInputHelper Self = new ExcelInputHelper();

public static DataSet ExecleDataSet(string filePath)
{
string OleDbConnection = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filePath + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn = new OleDbConnection(OleDbConnection);
try
{
conn.Open();
}
catch (Exception ee)
{
if (ee.Message.Contains("外部表不是预期的格式"))
{
OleDbConnection = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filePath + ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'";
conn.ConnectionString = OleDbConnection;
conn.Open();
}
else
{
Log.Log4NetUtility.Error(Self, "无法打开文件");
return null;
}
}

DataSet ds = new DataSet();
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
odda.Fill(ds);
conn.Close();
return ds;
}
}
}

原文地址:https://www.cnblogs.com/zhang-wenbin/p/5773595.html