Excel导入导出DataGridView
2021-01-25 12:12
标签:字符 exception closed office style new object dbconnect first /// 网上查找的方法,忘记在哪找的了,在这记录下: /// Excel导入导出DataGridView 标签:字符 exception closed office style new object dbconnect first 原文地址:https://www.cnblogs.com/20191204C/p/12016295.html 1 ///
/// excel表保存到dataTable中
///
/// excel表路径
///
private static DataTable ExcelToDataTable(string path)
{
DataTable dt = new DataTable();
try
{
//连接字符串
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;"; // Office 07及以上版本 不能出现多余的空格 而且分号注意
//string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;"; //Office 07以下版本
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字
string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一个sheet的名字
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName); //查询字符串
//string sql = string.Format("SELECT * FROM [{0}] WHERE [日期] is not null", firstSheetName); //查询字符串
OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
DataSet set = new DataSet();
ada.Fill(set);
dt = set.Tables[0];
}
return dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
} 1 ///
/// excel表保存到dataTable中
///
/// excel表路径
///
private static DataTable ExcelToDataTable(string path)
{
DataTable dt = new DataTable();
try
{
//连接字符串
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;"; // Office 07及以上版本 不能出现多余的空格 而且分号注意
//string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;"; //Office 07以下版本
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字
string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一个sheet的名字
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName); //查询字符串
//string sql = string.Format("SELECT * FROM [{0}] WHERE [日期] is not null", firstSheetName); //查询字符串
OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
DataSet set = new DataSet();
ada.Fill(set);
dt = set.Tables[0];
}
return dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
下一篇:C# 获取网页内容
文章标题:Excel导入导出DataGridView
文章链接:http://soscw.com/index.php/essay/46781.html