上传读取Excel文件数据

         /// <summary>
/// 上传读取Excel文件数据
/// 来自http://www.cnblogs.com/cielwater
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
public ActionResult AreaExcelFile(FormCollection form)
{
HttpPostedFileBase fileField = Request.Files["fileField"];
string path = Server.MapPath("~/Excel");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string flieName = fileField.FileName;
string fileExt = Path.GetExtension(flieName).ToLower().Substring();
//验证是否为Excel文件
if (fileExt != "xls" && fileExt != "xlsx")
{
ModelState.AddModelError("file", "您选择的不是Excel文件");
return View("ExcelFile");
}
string FileName = path + flieName.Substring(flieName.LastIndexOf("\\"));
fileField.SaveAs(FileName);
//读取excel文件,转换成dataset
string strConn = "";
if (fileExt == "xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=Excel 8.0;";
}
else if (fileExt == "xlsx")
{
strConn = "Provider= Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
}
DataSet ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
//获取Excel表结构
System.Data.DataTable sTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
conn.Dispose();
//遍历Excel文件所有表
foreach (DataRow ExcelTable in sTable.Rows)
{
//读取表
OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + ExcelTable[] + "]", strConn);
//写入DataSet
oada.Fill(ds);
//后面直接处理ds中的数据则可以
}
}
}
上一篇:js解析php返回的json数据无法获取length的问题分析


下一篇:在JS和.NET中使用JSON (以及使用Linq to JSON定制JSON数据)