1. 程式人生 > >.NET Excel匯入

.NET Excel匯入

前端程式碼:

html:

<form enctype="multipart/form-data" id="file-form">
<p>
<h3 style="color:red">上傳的Excel要與指標項名字一致</h3>


<input type="file" name="filed" id="filed" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

<button type="button" class="btn-sm btn-primary pull-right" id="btn-Search" onclick="importExcel()"><i class="fa fa-upload"></i>匯入Excel</button>
</p>
</form>

 

 

js:

// 匯入Excel
function importExcel() {
var formData = new FormData()
//多個才each
//$.each($("#filed")[0].files, function (index, obj) {
// formData.append("cusFile", obj);
//});
console.log($("#filed")[0].files[0]);

formData.append("cusFile", $("#filed")[0].files[0]);
$.ajax({
url:'/FormInfo/UploadExcelData',
type: 'POST',
data: formData,
async: false,
cache: false, //告訴瀏覽器不快取
contentType: false, //因為data值是FormData物件,不需要對資料做處理。
processData: false,
success: function (data) {
alert(data);
$("#filed").val() = "";
$("#importExcelModal").modal('hide');
}
});
}

 

 

 

 

後端程式碼:

/// <summary>
/// 匯入
/// </summary>
/// <param name="path">沒有什麼用處</param>
/// <returns></returns>
public ActionResult UploadExcelData(string path)
{
HttpPostedFileBase files = Request.Files["cusFile"];//與formData.append("cusFile", $("#filed")[0].files[0]);的""要一直
if (files == null)
{
return Content("請選擇要上傳Excel檔案");
}
string name = files.FileName;
string itemName = name.Substring(0, name.IndexOf("."));
//判斷是不是Excel檔案
string currFileExtension = name.Substring(name.LastIndexOf("."));
if (currFileExtension != ".xlsx" && currFileExtension != ".xls")
{
return Content("請上傳Excel檔案");
}

Session["mathpath"] = name;

//Resources/ImportExcel/  存放的路徑
string mathpath = HttpRuntime.AppDomainAppPath + "Resources/ImportExcel/" + name;
files.SaveAs(mathpath);

path = HttpRuntime.AppDomainAppPath + "Resources/ImportExcel/" + name;
DataTable dt = Import_Excel(path, "sheet1");
if (dt.Rows.Count == 0)
{
return Content("匯入失敗,請選擇有效檔案");
}

System.Transactions.TransactionOptions transactionOptions = new System.Transactions.TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead;
using (var trans = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
{
try
{
foreach (DataRow dr in dt.Rows)
{
//對資料進行操作

......

}
}
trans.Complete();//就這句就可以了。

}
catch (Exception e)
{
return Content("列錯誤,請選擇有效檔案");
}
}
return Content("匯入成功!");

}

/// <summary>
/// 查詢Excel表
/// </summary>
/// <param name="filePath"></param>
/// <param name="SheetName"></param>
/// <returns></returns>
public DataTable Import_Excel(string filePath, string SheetName)
{
try
{
string currFileExtension = filePath.Substring(filePath.LastIndexOf("."));
//連線字串
string sqlconn = string.Empty;
if (currFileExtension == ".xlsx")
{
sqlconn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; // Office 07及以上版本
}
else if (currFileExtension == ".xls")
{
sqlconn = @"Provider=Microsoft.JET.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; //Office 07以下版本
}

string[] str = GetExcelSheetNames(filePath);//17-4-10 替換

string sql = @"select * from [" + SheetName + "$]";
using (OleDbConnection conn = new OleDbConnection(sqlconn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn))
{
System.Data.DataTable dt = new System.Data.DataTable();
adapter.Fill(dt);
return dt;
}
}
}
catch
{

DataTable ss = new DataTable();
return ss;
}

}
public String[] GetExcelSheetNames(string fileName)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
string connString = string.Empty;
string FileType = fileName.Substring(fileName.LastIndexOf("."));
if (FileType == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileName + ";Extended Properties=Excel 8.0;";
else//.xlsx
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
// 建立連線物件
objConn = new OleDbConnection(connString);
// 開啟資料庫連線
objConn.Open();
// 得到包含資料架構的資料表
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// 新增工作表名稱到字串陣列
foreach (DataRow row in dt.Rows)
{
string strSheetTableName = row["TABLE_NAME"].ToString();
//過濾無效SheetName
if (strSheetTableName.Contains("$") && strSheetTableName.Replace("'", "").EndsWith("$"))
{
excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length - 1);
}
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
// 清理
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}