不在 asp.net mvc 模式下导入Excel文件数据到数据库,你会吗?
public DataTable GetTableFromExcel(string sheetName, string filePath)
{
const string connStrTemplate = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;";
DataTable dt = null;
if (!System.IO.File.Exists(filePath))
{
// don't find file
return null;
}
OleDbConnection conn = new OleDbConnection(string.Format(connStrTemplate, filePath));
try
{
conn.Open();
if (sheetName == null || sheetName.Trim().Length == 0)
{
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
}
else
{
sheetName += "$";
}
string strSQL = "Select * From [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSQL, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dt = ds.Tables[0];
}
catch(Exception ex)
{
throw ex;
}
return dt;
}
sheetName:excel中单个sheet的名称;
filePath:excel文件物理路径;
用上面这个方法读取excel中某个sheet的所有数据,注意数据格式要统一;既然数据源已经得到,那么再插入数据库就不是什么大问题吧?