.NET 上傳並解析CSV文件存庫
阿新 • • 發佈:2017-12-28
nco eat public reader new csv文件 err replace path
1.前端:
放置瀏覽按鈕
<div class="row inner_table text-center"> <input id="fileId" type="file" name="fileString" class="file "> </div>
2. JS:
註冊瀏覽按鈕的事件
var ChoseFile = function () { $("input[name=fileString]") .change(function () { varfilePath = $("[name=‘fileString‘]"); //讀取文件內容 var formData = new FormData(); formData.append(‘file[]‘, filePath[0].files[0]); $.ajax({ url: "XXXXXXXX入庫鏈接", type: ‘POST‘, data: formData, async:false, cache: false, contentType: false, processData: false, success: function (returndata) { alert("上傳成功"); }, error: function (returndata) { alert("上傳失敗"); } }); }); }
3 controller:
[CustomAuthorize(AuthType.Authrozied)] public JsonResult DataImport(FormCollection form) { string zipDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "templateFiles"); string masterFile = Path.Combine(zipDir, "template" + ".csv"); if (!Directory.Exists(zipDir)) { Directory.CreateDirectory(zipDir); } var file = Request.Files[0];
//上傳 file.SaveAs(masterFile); DataTable dt = GetCSVToData(masterFile); List<ScheduleTableInfo> infos = new List<ScheduleTableInfo>(); foreach (DataRow dataRow in dt.Rows) { ScheduleTableInfo info = new ScheduleTableInfo(); info.TemplateName = dataRow["標題名1"].ToString(); info.SumLevelName = dataRow["標題名2"].ToString(); infos.Add(info); } //執行入庫操作 int value = _client.ImportData(infos); var jsonStr = JsonConvert.SerializeObject(infos, new DataTableConverter(), new JavaScriptDateTimeConverter()); jsonStr = jsonStr.Replace("\\\\n", "\\r"); var result = Json(jsonStr, JsonRequestBehavior.AllowGet); return result; }
功能子函數:
private DataTable GetCSVToData(string strCsvPath, bool hasHeader = true, bool needLineNo = false) { CSVReader csvReader = null; try { csvReader = new CSVReader(strCsvPath, FileEncoding.GetType(strCsvPath)); DataTable dt = csvReader.GetTable(1, -1, hasHeader); return dt; } catch (Exception ex) { LogService.Debug("解析csv文件錯誤:" + ex); return null; } finally { if (csvReader != null) { csvReader.Dispose(); } } }
導入文件,獲取文件位置
.NET 上傳並解析CSV文件存庫