判斷檔案是否存在、開檔寫及存Excel以及特殊存取ajax回傳值

public ActionResult Query(HttpPostedFileBase[] files)
        {
        //取得路徑 路徑為IIS的根目錄下的Temp 不管發佈在哪
            string path = HttpContext.Server.MapPath("../Temp/");
            //判斷是否存在資料夾,不存在則建立
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            //走訪回傳資料
            try
            {
                foreach (HttpPostedFileBase file in files)
                {
                    //獲取Path,取IIS根目錄,並串起新newPath
                    string newPath = path + file.FileName;
                    //儲存進某個地方以方便讀取
                    file.SaveAs(newPath);

                    //開啟xlsx
                    XSSFWorkbook workbook = new XSSFWorkbook(newPath);
                    //RollBack
                    TransactionScope TS = new TransactionScope();
                    try
                    {
                        //建立Count 用於計算位置
                        int SheetCount = 0;
                        int RowCount = 0;
                        //走訪workbook
                        while (SheetCount < workbook.Count)
                        {
                            //取得目標Sheet
                            ISheet Sheet = workbook.GetSheetAt(SheetCount);
                            //取目標SheetRowCount走訪用
                            int iRow = Sheet.LastRowNum;
                            //走訪Sheet
                            while (RowCount <= iRow)
                            {
                                //取每一條Row
                                IRow row = Sheet.GetRow(RowCount);
                             }
                            SheetCount++;
                        }
                        //關閉並且刪除Workbook 保持Temp乾淨
                        //RollBack
                        TS.Complete();
                        TS.Dispose();
                    }
                    catch (Exception e)
                    {
                        ViewBag.msg = file.FileName + e.Message;
                    }
                    finally
                    {
                        workbook.Close();
                        System.IO.File.Delete(newPath);
                        TS.Dispose();
                    }
                }
            }
            //IO錯誤
            catch (IOException e)
            {
                ViewBag.msg = e.Message;
            }
            //其餘錯誤
            catch (Exception e)
            {
                ViewBag.msg = e.Message;
            }

            //成功完成整趟寫入
            if (ViewBag.msg == null)
            {
                TempData["msg"] = "成功寫入";
                ViewBag.msg = "成功寫入";
            }

            return View();

}

前端
這邊寫的比較特殊 原因是因為用這種寫法可以讀出ViewBag 因為Submit是重新再開啟一個新的View 因此ViewBag.msg會沒辦法動作


<input type="file" id="fileupload" name="fileupload" accept=".xlsx" multiple="multiple" />

<input type="submit" id="fileSubmit" name="fileSubmit" class="btn btn-primary" value="寫入資料庫" />

@if (ViewBag.msg != null)
{
<alert>
    @ViewBag.msg
</alert>
}

<script>
    $("#fileSubmit").on("click", function () {
        var file = $("#fileupload").val;
        if (file == null || file == "") {
            alert("無上傳檔案");
        } else {
            var file = document.getElementById("fileupload").files;
            var fileData = new FormData();
            for (var i = 0; i < file.length; i++) {
                fileData.append("files", file[i]);
            }
            $.ajax({
                url: '@Url.Action("Query", "CmPreMemberImport")',
                contentType: false,
                async: true,
                type:"POST",
                cache: false,
                processData: false,
                data: fileData,
                error: function (jq, status, error) {
                    alert("File:" + error);
                },
                success: function (data, status, jq) {
                    // 第一步:匹配加載的頁面中是否含有目標字串
                    var regDetectJs = /<alert>(.|\n|\r\n)*?<\/alert>/ig;
                    var jsContained = data.match(regDetectJs); //ajaxLoadedData為ajax獲取到的數據

                    // 第二步:如果包含目標字串,則一段一段的取出再加載執行
                    if (jsContained) {
                        // 分段取出目標字串正則
                        var regGetJS = /<alert>((.|\n|\r\n)*)?<\/alert>/im;

                        // 按順序分段執行
                        var jsNums = jsContained.length;
                        //走訪捕捉到的Data
                        for (var i = 0; i < jsNums; i++) {
                            var jsSection = jsContained[i].match(regGetJS);
                            if (jsSection) {
                                //切出字串後alert出去
                                alert(jsSection[1]);
                            }
                        }
                    }
                },  
            })
        }
    })
</script>

--修改後寫法
[HttpPost]
public async Task<IActionResult> Query(List<IFormFile> files)
{
    if (files == null || files.Count == 0)
        return Json(new { success = false, message = "未上傳檔案" });

    try
    {
        foreach (var file in files)
        {
            if (file.Length == 0)
                continue;

            // 直接讀取檔案,不存 Temp
            await using var stream = file.OpenReadStream();

            // NPOI Workbook
            var workbook = new XSSFWorkbook(stream);

            // TransactionScope 
            using var scope = new TransactionScope(
                TransactionScopeAsyncFlowOption.Enabled);

            for (int sheetIndex = 0; sheetIndex < workbook.NumberOfSheets; sheetIndex++)
            {
                var sheet = workbook.GetSheetAt(sheetIndex);

                for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++)
                {
                    var row = sheet.GetRow(rowIndex);
                    if (row == null) continue;

                    // TODO
                    // var cellValue = row.GetCell(0)?.ToString();
                }
            }

            scope.Complete();
        }

        return Json(new { success = true, message = "成功寫入資料庫" });
    }
    catch (Exception ex)
    {
        return Json(new { success = false, message = $"匯入失敗: {ex.Message}" });
    }
}

前端
<input type="file" id="fileupload" multiple accept=".xlsx" />
<button id="fileSubmit" class="btn btn-primary">寫入資料庫</button>

<div id="resultMsg" style="margin-top:10px;color:blue;"></div>

$("#fileSubmit").on("click", function () {

    let files = $("#fileupload")[0].files;

    if (files.length === 0) {
        alert("請選擇檔案");
        return;
    }

    let formData = new FormData();

    for (let i = 0; i < files.length; i++) {
        formData.append("files", files[i]);
    }

    $.ajax({
        url: '@Url.Action("Query", "CmPreMemberImport")',
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function (res) {

            $("#resultMsg").text(res.message);

            if (!res.success) {
                alert("錯誤:" + res.message);
            }
        },
        error: function () {
            alert("上傳失敗,請稍後再試");
        }
    });
});



留言

這個網誌中的熱門文章

無法載入檔案或組件 'System.IO.Compression' 或其相依性的其中之一。

MongoDB 入門

javascript 更改屬性及創建標籤