利用OpenXml讀取、導出Excel


     OpenXml是通過 XML 文檔提供行集視圖。由於OPENXML 是行集提供程序,因此可在會出現行集提供程序(如表、視圖或 OPENROWSET 函數)的 Transact-SQL 語句中使用 OPENXML。

     效果圖:

    使用它的時候,首選的下載安裝這個程序集,下載地址:http://www.microsoft.com/en-us/download/details.aspx?id=30425

     安裝好了在項目當中引用如下2個

    

   前台彈出框用的是 jBox這個js插件,我用了ajax請求的方式來上傳js部分

function ImportExlDataGridRows() {
    var html = "<form  enctype=\"multipart/form-data\" method=\"post\"> <div style='padding:10px;'>請選擇導入的文件:(*.xlsx) <a href=\"download.aspx?ParamValue=1\" rel=\"external\" style=\"color:#000; background:#CCC; width:80px; border:1px solid #09F\" >下載模板</a></div>";
    html += "<div style='padding:10px;'><input type=\"file\" name=\"uploadImg\" id=\"uploadImg\"  style=\"  width:320px; border:1px solid #09F\" /></div>";
    html += "</form> ";
    var submit = function (v, h, f) {
        //判斷是否有選擇上傳文件  
        var imgPath = $("#uploadImg").val();
        if (imgPath == "") {
            alert("請選擇導入的文件!");
            return false;
        }
        //判斷上傳文件的后綴名  
        var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
        if (strExtension != 'xlsx' && strExtension != 'xls') {
            alert("請選擇導入的文件(*.xlsx)");
            return false;
        }
        $.ajaxFileUpload(
            {
                url:window.location.href,
                secureuri: false,
                fileElementId: 'uploadImg',
                dataType: 'json',
                data:{ "method":"file"},
                beforeSend: function () {
                    $.jBox.tip("正在加載導入", "loading"); 
                },
                complete: function () {
                   
                },
                success: function (data, status) {
                    //if (typeof (data.Success) != 'undefined') {
                    if (data.Success != '') {
                        $.jBox.tip(data.Msg);
                        }
                   // }
                },
                error: function (data, status, e) {
                    $.jBox.tip(e);
                }
            }
        )
         

        return true;
    };

    $.jBox(html, { title: "導入預防性維修派單", submit: submit });
}

后台方法

/// <summary>
        /// 導入exl
        /// </summary>
        public void FilePlanImport()
        {
            string pathWan = "";
            try
            {
                //Web站點下,附件存放的路徑 
                string strFileFolerInWebServer = ConfigurationManager.AppSettings["FileFolerInWebServer"];
                HttpFileCollection files = Request.Files;
                if (files.Count <=0) {
                    ResponseWriteSuccessORFail(false, "文件導入");
                    return;
                }
                HttpPostedFile postedFile = files[0];
                //context.Request.Files["Filedata"];
                string savepath = "";
                savepath = Server.MapPath(strFileFolerInWebServer) + "\\";//實際保存文件夾路徑
                string filename = postedFile.FileName;

                string sNewFileName = "年度生產設備保養計划表_" + DateTime.Now.ToString("yyyyMMddhhmmss");
                string sExtension = filename.Substring(filename.LastIndexOf('.'));
                if (!Directory.Exists(savepath))
                {
                    Directory.CreateDirectory(savepath);
                }
                  pathWan=savepath + @"\" + sNewFileName + sExtension;
                postedFile.SaveAs(pathWan);


                //保存到文件服務器上的名稱
 
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message + ex.StackTrace);
                ResponseWriteSuccessORFail(false, "文件導入");
                return;
               // context.Response.Write("Error: " + ex.Message);
            }
            DataTable data = null;
            int errRows = 0;//
            try
            {
                
                using (var document = SpreadsheetDocument.Open(pathWan, false))
                {

                    var worksheet = document.GetWorksheet();
                    var rows = worksheet.Descendants<Row>().ToList();
                    var sharedStringTable = document.GetSharedStringTable();

                    // 讀取Excel中的數據
                    IEnumerable<string> rowskey =  
                        new string[] {  "OUGUID","AccessoriesCategories" ,"AccessoriesSubclass" ,"MaintenanceMethod",
                        "Cycle" ,"CycleUnit","EffectiveDate" ,"ClosingDate","EarlyDays","WorkPermit","RepairBusiness"};
                    ExcelOpenXMLHelper.SetRows = rowskey;//這部分是需要讀取那些字段
                    data = ExcelOpenXMLHelper.ReadExcelData(rows, sharedStringTable);
                    
                    foreach (DataRow item in data.Rows)
                    {
                        
                       ....數據插入部分
                    }
                   
                }
                string msg = "文件導入成功:" + (data.Rows.Count - errRows) + ",錯誤:" + errRows;
                ResponseWriteSuccessORFail(true, msg);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message + ex.StackTrace);
                string msg = "文件導入成功:" + (data.Rows.Count - errRows) + ",錯誤:" + errRows;
                ResponseWriteSuccessORFail(false, msg);
            }
        }

  ExcelOpenXMLHelper這是對OpenXml的一些操作封裝成了helper類。

   

導出部分比較簡單

/// <summary>
        /// 導出Excel
        /// </summary>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        /// <param name="fileTemplatePath">
        /// The file template path.
        /// </param>
        /// <exception cref="Exception">
        /// </exception>
        private void ExcelOut(string filePath, string fileTemplatePath)
        {
            try
            {
                System.IO.File.Copy(fileTemplatePath, filePath);
            }
            catch (Exception ex)
            {
                throw new Exception("復制Excel文件出錯" + ex.Message);
            }

            using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, true))
            {
                var sheetData = document.GetFirstSheetData();
                OpenXmlHelper.CellStyleIndex = 1;

                ////寫標題相關信息
                 this.UpdateTitleText(sheetData);
                //循環rows數據寫入excl
                IEnumerable<string> rowskey =
                new string[] { "OUGUID","AccessoriesCategories" ,"AccessoriesSubclass" ,"MaintenanceMethod",
            "Cycle" ,"CycleUnit","EffectiveDate" ,"ClosingDate","EarlyDays","WorkPermit","RepairBusiness"};

                ExcelOpenXMLHelper.SetRows = rowskey;//這部分是需要讀取那些字段
                DataTable dt=BLL.BudgetBO();
                foreach (DataRow dr in dt.Rows)
	            {
		           foreach (string item in rowskey)
                    {
                        sheetData.SetCellValue(item, dr[item]);
                    }
                }
                // var str = OpenXmlHelper.ValidateDocument(document);驗證生成的Excel
            }
        }
        /// <summary>
        /// 修改標頭
        /// </summary>
        /// <param name="sheetData">
        /// The sheet data.
        /// </param>
        private void UpdateTitleText(SheetData sheetData)
        {
            sheetData.UpdateCellText("A1", "xx工信息");
            sheetData.UpdateCellText("A2", "制表時間:" + DateTime.Now.ToString("yyyy年MM月dd日HH時"));
            sheetData.UpdateCellText("G2", "制表人:admin");
        }

  以上就是利用OpenXml實現導出導入功能全部代碼,Helper類需要的可以留下郵箱。

  

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM