一、导出Excel
public enum ReportTemplateMode { WebOrder, WebOrderDetails, WebSend, WebSendDetails, } public class TemplateFileUtility { public static string CreateTemplateFile(ReportTemplateMode model) { string filePath = HttpContext.Current.Server.MapPath("~/Template"); string templateFile = string.Empty; string createFile = string.Empty; switch (model) { case ReportTemplateMode.WebOrder: case ReportTemplateMode.WebOrderDetails: case ReportTemplateMode.WebSend: case ReportTemplateMode.WebSendDetails: createFile = Guid.NewGuid() + ".xls"; templateFile = Path.Combine(filePath, model.ToString() + ".xls"); break; default: createFile = Guid.NewGuid() + ".xls"; templateFile = Path.Combine(filePath, model.ToString() + ".xls"); break; } createFile = Path.Combine(GetTempFile(), createFile); if (!File.Exists(templateFile)) { throw new Exception("Find Not TemplateFile Path: " + templateFile); } File.Copy(templateFile, createFile, true); File.SetAttributes(createFile, FileAttributes.Normal); return createFile; } public static string GetTempFile() { string tempFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp"); if (!System.IO.Directory.Exists(tempFile)) { System.IO.Directory.CreateDirectory(tempFile); } return tempFile; } } //点击"导出"按钮 protected void btn_Export_OnClick(object sender, EventArgs e) { GC.Collect(); string targetExcelFileName = TemplateFileUtility.CreateTemplateFile(ReportTemplateMode.WebOrder); OrderSearchFilter filter = GetFilter(); DataTable dtbl = BizOrder.ExportOrderListByFilter(filter); //Excel模型,用来操作Excel文件 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook excelWb = null; Microsoft.Office.Interop.Excel.Worksheet excelWs = null; Microsoft.Office.Interop.Excel.Range cellR = null; try { //打开Excel工作簿文件 excelWb = excel.Workbooks.Open(targetExcelFileName, System.Type.Missing, false, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing); excelWs = (Microsoft.Office.Interop.Excel.Worksheet)(excelWb.Sheets.get_Item(1)); //选择工作簿中第一个工作表 //查询条件 excelWs.Cells[2, 3] = this.txt_Keywords.Value; excelWs.Cells[3, 3] = GetSearchDate(); excelWs.Cells[2, 12] = this.ddl_OrderState.SelectedIndex == 0 ? string.Empty : this.ddl_OrderState.SelectedItem.Text; excelWs.Cells[3, 12] = this.ddl_PayState.SelectedIndex == 0 ? string.Empty : this.ddl_PayState.SelectedItem.Text; excelWs.Cells[2, 14] = HttpContextUtility.CurrentAdminUser.Username; excelWs.Cells[3, 14] = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); //把每一行数据写入Excel模型中 int startRow = 6; decimal numSource = 0, num = 0, settleAmount = 0, saleAmount = 0, expressAmount = 0; int i = 0; for (i = 0; i < dtbl.Rows.Count; i++) { cellR = excelWs.get_Range(excelWs.Cells[startRow + i, 1], excelWs.Cells[startRow + i, dtbl.Columns.Count]); cellR.Borders.Color = System.Drawing.ColorTranslator.ToOle(Color.Black); for (int j = 0; j < dtbl.Columns.Count; j++) { excelWs.Cells[startRow + i, j + 1] = dtbl.Rows[i][j].ToString(); if (j == 4) { numSource += decimal.Parse(dtbl.Rows[i][j].ToString()); } else if (j == 5) { num += decimal.Parse(dtbl.Rows[i][j].ToString()); } else if (j == 6) { settleAmount += decimal.Parse(dtbl.Rows[i][j].ToString()); } else if (j == 7) { saleAmount += decimal.Parse(dtbl.Rows[i][j].ToString()); } else if (j == 8) { expressAmount += decimal.Parse(dtbl.Rows[i][j].ToString()); } } } excelWs.Cells[startRow + i, 4] = "合计:"; excelWs.Cells[startRow + i, 5] = numSource.ToString("N2"); excelWs.Cells[startRow + i, 6] = num.ToString("N2"); excelWs.Cells[startRow + i, 7] = settleAmount.ToString("N2"); excelWs.Cells[startRow + i, 8] = saleAmount.ToString("N2"); excelWs.Cells[startRow + i, 9] = expressAmount.ToString("N2"); cellR = excelWs.get_Range(excelWs.Cells[startRow + i, 4], excelWs.Cells[startRow + i, 9]); cellR.Font.Bold = true; excelWb.Save(); } catch (Exception ex) { string info = ex.Message; Extensions.WriteLog("Order_List", "导出时发生异常:" + info); } finally { //关闭Excel,否则Excel文件将无法被打开 excel.Workbooks.Close(); excel.Quit(); } //向客户端发送文件... Response.Clear(); Response.AddHeader("Content-Disposition", "attachment;filename=excel.xls"); //设置回发内容为Excel Response.ContentType = "application/ms-excel"; Response.WriteFile(targetExcelFileName); //把刚刚生成的Excel文件写入Http流 Response.End(); }
二、读取Excel文件
public static DataTable ReaderExcelData(string filePath) { //创建Excel实例,获取worksheet Name var oExcel = new Microsoft.Office.Interop.Excel.Application(); object objMissing = System.Reflection.Missing.Value; var myBook = oExcel.Workbooks.Open(filePath, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing); Microsoft.Office.Interop.Excel.Sheets sheets = myBook.Worksheets; var ws = (Microsoft.Office.Interop.Excel.Worksheet)sheets.Item[1]; //获取工作簿名称 string wsName = ws.Name; oExcel.Quit(); //读取当前Excel的数据到DataTable中 DataTable table = ReaderExcelData(filePath, wsName); return table; } public static DataTable ReaderExcelData(string filePath, string worksheetName) { try { //连接字符串 String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\""; var myConn = new OleDbConnection(sConnectionString); string strCom = " SELECT * FROM [" + worksheetName + "$]"; myConn.Open(); var myCommand = new OleDbDataAdapter(strCom, myConn); var table = new DataTable(); myCommand.Fill(table); myConn.Close(); return table; } catch (Exception) { return null; } finally { try { //File.Delete(filePath);//返回数据后删除垃圾文件 } catch { } } }
三、MVC读取Excel文件
/*引用动态链接库文件:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,NPOI.OpenXmlFormats.dll*/ using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.Util; public ActionResult AliExpressOrderImport(HttpPostedFileBase filebase) { HttpPostedFileBase file = Request.Files["excelFile"]; string FileName = string.Empty; string SavePath = string.Empty; string errormsg = "无"; if (file == null || file.ContentLength <= 0) { ViewBag.error = "文件不能为空"; return View("Upload"); } else { string filename = Path.GetFileName(file.FileName); int filesize = file.ContentLength; string fileSuf = Path.GetExtension(filename);//获取文件扩展名 string filePre = Path.GetFileNameWithoutExtension(filename);//获取文件名称 FileName = filePre + DateTime.Now.ToString("yyyyMMddhhmmss") + fileSuf; SavePath = AppDomain.CurrentDomain.BaseDirectory + "ExcelTemplete\\uploads\\" + FileName; file.SaveAs(SavePath); } List<Chiang.Entity.SCMV2DB.Country> listCountry = cmpdbuntility.Entities<Chiang.Entity.SCMV2DB.Country>("SELECT * FROM Country ").ToList(); StringBuilder sb = new StringBuilder(); string sellerID = Request["SellerID"]; string insertSql = string.Empty; int intRow=0; try { IWorkbook HssWorkBook; using (FileStream fs = new FileStream(SavePath, FileMode.Open, FileAccess.Read)) { HssWorkBook = new XSSFWorkbook(fs); ISheet sheet = HssWorkBook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); int num = 0; while (rows.MoveNext()) { if (num == 0) { num++; continue; } IRow row = (XSSFRow)rows.Current; if (row.GetCell(0) == null && row.GetCell(1) == null) { errormsg = "文件内容有异常,请检查第一行"; break; } else if (string.IsNullOrEmpty(row.GetCell(0).ToString()) && string.IsNullOrEmpty(row.GetCell(1).ToString())) { errormsg = "首行首列不能为空"; break; } DataRow frow = cmpdbuntility.FirstRow("SELECT * FROM [dbo].[OrdersFromExcel] WHERE ORDERID={0} ", row.GetCell(1).ToString()); if (frow != null) { errormsg = "AliExpress订单: " + row.GetCell(1).ToString() + "已经上传过,不能重复上传."; break; } string orderStatus = row.GetCell(1).ToString().Trim(); // 资金未到账/等待您发货/等待买家收货 if (orderStatus != "等待您发货") { continue; } string orderID = row.GetCell(0).ToString().Trim(); string productInfo = row.GetCell(11).ToString(); string countryName = row.GetCell(15).ToString().Trim(); string countryCode = string.Empty; var country = listCountry.Where(t => t.English.Contains(countryName) || countryName.Contains(t.English)).FirstOrDefault(); if (country != null) { countryCode = country.Code; } else { sb.Append("订单号:" + orderID + " 找不到对应的国家编号;"); } insertSql = string.Format(@"INSERT INTO [dbo].[OrdersFromExcel] (OrderID,Status,Saler,Buyer_Name,Buyer_Email,OrderDate,PaydOn,TotalAmount,ShippingAmount,OrderAmount,DiscountAmount,ProductDetails,Remarks, Address1,ReceiverName,CountryName,Province,City,Address2,PostCode,Tel,Mobile,ShippingMethod,DeliveryLimitedDate, TrackingNumber,DeliveryDate,ConfirmDate,SellerID,CountryCode,SkuDetails,ProductAttribute,ImportDate) VALUES('{0}','{1}','{2}','{3}','{4}','{5}',case when '{6}'='' then NULL else '{6}' end,'{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}',NULL,'{18}','{19}','{20}','{21}',case when '{22}'='' then NULL else '{22}' end,NULL,NULL,NULL,'{23}','{24}','{25}','{26}',getdate())", orderID, orderStatus, row.GetCell(2).ToString().Replace("'", "''"), row.GetCell(3).ToString().Replace("'", "''"), "[email protected]", //row["买家邮箱"].ToString().Replace("'", "''"), Convert.ToDateTime(row.GetCell(5).ToString()).ToString(), row.GetCell(6).ToString() == "" ? "" : Convert.ToDateTime(row.GetCell(6).ToString()).ToString(), row.GetCell(7).ToString(), row.GetCell(8).ToString(), row.GetCell(9).ToString(), row.GetCell(10).ToString() == "" ? "0" : row.GetCell(10).ToString(), row.GetCell(11).ToString().Replace("'", "''"), row.GetCell(12).ToString().Replace("'", "''"), //Remarks row.GetCell(13).ToString().Replace("'", "''"), //收货地址 row.GetCell(14).ToString().Replace("'", "''"), // countryName.Replace("'", "''"), row.GetCell(16).ToString().Replace("'", "''"), row.GetCell(17).ToString().Replace("'", "''"), row.GetCell(19).ToString().Replace("'", "''"), row.GetCell(20).ToString().Replace("'", "''"), row.GetCell(21).ToString().Replace("'", "''"), row.GetCell(22).ToString().Replace("'", "''"), row.GetCell(23).ToString() == "" ? "" : Convert.ToDateTime(row.GetCell(23).ToString()).ToString(), sellerID, countryCode, skuDetials.ToString(), productAttribute ); var succ = cmpdbuntility.NonQuery(insertSql); if (succ > 0) { intRow++; } } } ViewBag.error = "AliExpress导入成功" + intRow + "个订单;"+sb.ToString(); System.IO.File.Delete(SavePath); } catch (Exception ex) { ViewBag.error = "AliExpress导入成功" + intRow.ToString() + "个订单;异常信息:" + ex.Message + "。更多:" + insertSql + " ," + sb.ToString(); } return View("Upload"); }