您的位置:首页 > 其它

.net导入Excel文件返回DataSet数据集

2016-10-20 15:49 225 查看
#region 获取数据集
protected DataSet GetDataSet(string filePath)
{
//2010以前版本连接字符串
//string Connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");

//IMEX=1 一共有三种模式 0表示导出 1 导入 2表示混合模式 在读取Excel数据有金额类型的后面带小数点最好去掉IMEX属性
//HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
string Connstr2010 = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Server.MapPath("~/") + filePath + "';Extended Properties='Excel 12.0;HDR=NO'");
OleDbConnection Conn = new OleDbConnection(Connstr2010);
//创建ArrayList对象 存放所有sheetname
ArrayList sheetNamelist = new ArrayList();
DataSet dsExcel = new DataSet();
try
{
if (Conn.State == ConnectionState.Closed)//检测conn是否处于开启状态
{
Conn.Open();
}
DataTable dtExcelSchema = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

string sheetName = string.Empty;

for (int j = 0; j < dtExcelSchema.Rows.Count; j++)
{

sheetName = dtExcelSchema.Rows[j]["TABLE_NAME"].ToString();
//sheet名称
if (sheetName.ToLower().IndexOf("database") != -1)
continue;
else
sheetNamelist.Add(sheetName);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString(), ex);
}
finally
{
Conn.Close();
}
try
{
string strSQL = string.Empty;
for (int i = 0; i < sheetNamelist.Count; i++)
{

strSQL = "select * from [" + sheetNamelist[i].ToString() + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSQL, Conn);
DataTable dtExcel = new DataTable(sheetNamelist[i].ToString());
da.Fill(dtExcel);

dsExcel.Tables.Add(dtExcel);
}

return dsExcel;
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString(), ex);
return null;
}
finally
{

}
}
#endregion
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  导入Excel