先天下之忧而忧,后天下之乐而乐。——宋·范仲淹《岳阳楼记》 楠少博客 阅读文章 C# 操作Excel、PDF 楠少 2018-10-01 6666666 8888888 CSharp 数据导出 摘要因为手边有个项目,其需求中有关于数据读写导入导出的操作。巴拉巴拉巴拉。 所需环境:Visual Studio、 所用到的dll运行库:Spire.Xls( 官方网站 ) 该项目是用C#编写的,采用了三层架构、MVC模式。 **目录 (Table of Contents)** [TOC] ### 最近依旧很忙 忙的没时间更博客,本来就是demo的博客到底能撑多久呢?这也是个迷。。。 ### 正文 #### 前因后果 因为手边有个项目,其需求中有关于数据读写导入导出的操作。巴拉巴拉巴拉。 + 所需环境:Visual Studio、 + 所用到的dll运行库:Spire.Xls( [官方网站](https://www.e-iceblue.com/ "官方网站") ) + 该项目是用C#编写的,采用了三层架构、MVC模式。 #### 开始 所需 spire.xls 需要授权使用(付费),也有体验版本(但是生成的pdf会有显眼的版权信息),我用了最新的体验版,后来spire开发团队邮件联系了我,并表示可以去掉那一串版权信息,那我当然去索要了,哈哈哈哈。附上部分邮件截图:  #### 直接上代码: pdf导出部分: ```csharp public static string ShenQingBiaoDownload(ShenQingBiao s) { string sourcePath = AppDomain.CurrentDomain.BaseDirectory + "File/SQBModel.xls"; // read 模式 防止文件被占用 FileStream file = new FileStream(sourcePath, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(file); ISheet sheet1 = hssfworkbook.GetSheet("Sheet1"); // 写数据 //=========================================================== int year = int.Parse(DateTime.Now.ToString("yyyy")); if (int.Parse(DateTime.Now.ToString("MM")) >= 10) { year++; } sheet1.GetRow(0).GetCell(0).SetCellValue(sheet1.GetRow(0).GetCell(0).ToString().Replace("YEAR", year.ToString())); sheet1.GetRow(1).GetCell(0).SetCellValue(sheet1.GetRow(1).GetCell(0).ToString().Replace("YEAR", year.ToString())); sheet1.GetRow(1).GetCell(2).SetCellValue(s.KaoShengHao); sheet1.GetRow(1).GetCell(7).SetCellValue(DateTime.Now.ToLongDateString().ToString()); sheet1.GetRow(2).GetCell(1).SetCellValue(s.Name); sheet1.GetRow(2).GetCell(3).SetCellValue(s.XingBie); sheet1.GetRow(2).GetCell(5).SetCellValue(s.MingZu); // 插入照片 byte[] bytes = System.IO.File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory+s.ZhaoPian); int pictureIdx = hssfworkbook.AddPicture(bytes,PictureType.JPEG); HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.CreateDrawingPatriarch(); //add a picture HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 140, 180, 7, 3, 9, 7); HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx); string d = s.IdNumber.Substring(6, 4) + "-" + s.IdNumber.Substring(10, 2) + "-" + s.IdNumber.Substring(12, 2); sheet1.GetRow(4).GetCell(1).SetCellValue(d); sheet1.GetRow(4).GetCell(4).SetCellValue(s.ZhengZhi); sheet1.GetRow(5).GetCell(1).SetCellValue(s.IdNumber); sheet1.GetRow(5).GetCell(4).SetCellValue(s.HomePhone); sheet1.GetRow(6).GetCell(1).SetCellValue(s.XueXiao); sheet1.GetRow(6).GetCell(4).SetCellValue(s.Phone); sheet1.GetRow(7).GetCell(1).SetCellValue(s.HomeAddress); sheet1.GetRow(7).GetCell(5).SetCellValue(s.YouBian); sheet1.GetRow(9).GetCell(1).SetCellValue(s.S_WuLi); sheet1.GetRow(9).GetCell(2).SetCellValue(s.S_HuaXue); sheet1.GetRow(9).GetCell(3).SetCellValue(s.S_LiShi); sheet1.GetRow(9).GetCell(4).SetCellValue(s.S_DiLi); sheet1.GetRow(9).GetCell(5).SetCellValue(s.S_ZhengZhi); sheet1.GetRow(9).GetCell(6).SetCellValue(s.S_ShengWu); sheet1.GetRow(9).GetCell(8).SetCellValue(s.S_XinXi); sheet1.GetRow(10).GetCell(1).SetCellValue( s.MianWenHuaZC +"\n\n"+ s.MianWenHuaZS + "\n\n当前状态:" + s.MianShiZT ); sheet1.GetRow(11).GetCell(1).SetCellValue(s.ZF + "\n\n" + s.JiaFenZC + "\n\n" + s.JiaFenZS + "\n\n当前状态:" + s.JiaFenZT); sheet1.GetRow(12).GetCell(0).SetCellValue(s.Zhu.Replace("<br>","\n")); // 强制执行更新计算 (用于公式等) sheet1.ForceFormulaRecalculation = true; string domain = AppDomain.CurrentDomain.BaseDirectory; string path = "File/ShenQingBiao/申请表_"+s.Name; file = new FileStream(domain+path + ".xls", FileMode.Create); hssfworkbook.Write(file); file.Close(); Excel2PDF(domain+path + ".xls", domain+path + ".pdf"); return "../" + path + ".pdf"; } ``` Excel 导出部分: ```csharp public static string DaoChuJFCY() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet = wb.CreateSheet("sheet1"); int hangShu = -1; IRow rows = (HSSFRow)sheet.CreateRow(++hangShu); rows.CreateCell(0).SetCellValue("身份证号码"); rows.CreateCell(1).SetCellValue("物理成绩"); rows.CreateCell(2).SetCellValue("化学成绩"); rows.CreateCell(3).SetCellValue("历史成绩"); rows.CreateCell(4).SetCellValue("地理成绩"); rows.CreateCell(5).SetCellValue("政治成绩"); rows.CreateCell(6).SetCellValue("生物成绩"); rows.CreateCell(7).SetCellValue("信息技术成绩"); rows.CreateCell(8).SetCellValue("小高考加分"); rows.CreateCell(9).SetCellValue("申请政策"); rows.CreateCell(10).SetCellValue("奖项名称"); rows.CreateCell(11).SetCellValue("奖项类型"); rows.CreateCell(12).SetCellValue("政策加分"); rows.CreateCell(13).SetCellValue("累计加分"); rows.CreateCell(14).SetCellValue("审核结果"); DataTable dt = JiaFenShenQingManage.BuMenDaoChuCY(); foreach (DataRow row in dt.Select()) { rows = (HSSFRow)sheet.CreateRow(++hangShu); rows.CreateCell(0).SetCellValue(row["IdNumber"].ToString()); rows.CreateCell(1).SetCellValue(row["S_WuLi"].ToString()); rows.CreateCell(2).SetCellValue(row["S_HuaXue"].ToString()); rows.CreateCell(3).SetCellValue(row["S_LiShi"].ToString()); rows.CreateCell(4).SetCellValue(row["S_DiLi"].ToString()); rows.CreateCell(5).SetCellValue(row["S_ZhengZhi"].ToString()); rows.CreateCell(6).SetCellValue(row["S_ShengWu"].ToString()); rows.CreateCell(7).SetCellValue(row["S_XinXi"].ToString()); rows.CreateCell(8).SetCellValue(row["XiaoGaoKao"].ToString()); rows.CreateCell(9).SetCellValue(row["ZhengCe"].ToString()); rows.CreateCell(10).SetCellValue(row["MingCheng"].ToString()); rows.CreateCell(11).SetCellValue(" [ " + row["LeiBie"].ToString() + " - " + row["JiBie"].ToString() + " - " + row["DengJi"].ToString() + " ] "); rows.CreateCell(12).SetCellValue(row["ZhengShu"].ToString()); rows.CreateCell(13).SetCellValue((int)row["XiaoGaoKao"] + (int)row["ZhengShu"]); } string path = "File/Admin/加分存疑" + DateTime.Now.ToString("MMdd") + ".xls"; string str = AppDomain.CurrentDomain.BaseDirectory + path; FileStream file = new FileStream(str, FileMode.Create); wb.Write(file); file.Close(); return "<script>window.open('../" + path + "')</script>"; } ``` Excel 转 PDF : /// <summary> /// excel 转 pdf /// </summary> /// <param name="ExcelPath"></param> /// <param name="PdfPath"></param> public static void Excel2PDF(string ExcelPath, string PdfPath) { Workbook workbook = new Workbook(); workbook.LoadFromFile(ExcelPath); Spire.License.LicenseProvider.SetLicenseFileName(@"../File/license.elic.xml"); workbook.SaveToFile(PdfPath, FileFormat.PDF); DeleteFile(ExcelPath); } Excel 导入部分: ```csharp /// <summary> /// 管理员 考试院信息导入接口 /// </summary> /// <returns></returns> [HttpPost] public string XGKDaoRu(string xgk) { var file = Request.Files[0]; string mapPath = Server.MapPath("../File/Admin/"); string[] types = file.FileName.Split('.'); // 获取扩展名 string type = types[types.Length - 1]; string path = mapPath + "xgk" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + type; // 生成目标路径 file.SaveAs(path); ISheet sht; if (type == "xls") { HSSFWorkbook wb = new HSSFWorkbook(new FileStream(path, FileMode.Open)); sht = wb.GetSheetAt(0); } else { XSSFWorkbook wb = new XSSFWorkbook(new FileStream(path, FileMode.Open)); sht = wb.GetSheetAt(0); } // 取行Excel的最大行数 int rowsCount = sht.PhysicalNumberOfRows; // 获取所有行中的最大列数(手动调整第一行为最大)。 int colsCount = sht.GetRow(0).PhysicalNumberOfCells; // 存放必要列名 string[] Keys = { "考籍号", "姓名", "性别", "考生号", "证件号码","联系电话1", "联系电话2", "民族", "毕业中学","政治面貌", "物理成绩","化学成绩","历史成绩","地理成绩", "政治成绩","生物成绩", "信息技术", "专业1", "专业2", "专业3", "专业4", "专业5", "专业6", "是否服从" }; // 用以存放对应列名的下标 int[] cou = new int[Keys.Length]; int count = 0; // 存入下标位置 for (int searchindex = 0; searchindex < colsCount; searchindex++) { for (int i = 0; i < Keys.Length; i++) { if (sht.GetRow(0).GetCell(searchindex).ToString() == Keys[i]) { cou[count++] = searchindex; } } } // 将对应信息加入到对应位置 IList<StudentInfo> models = new List<StudentInfo>(); IList<ZhiYuan> Zmodels = new List<ZhiYuan>(); for (int rowIndex = 1; rowIndex < rowsCount; rowIndex++) { StudentInfo model = new StudentInfo(); ZhiYuan Zmodel = new ZhiYuan(); int i = 0; model.KaoJiHao = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.Name = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.XingBie = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.KaoShengHao = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.IdNumber = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.Phone = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.HomePhone = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.MingZu = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); model.XueXiao = int.Parse(sht.GetRow(rowIndex).GetCell(cou[i++]).ToString()); string zz = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); if (zz.Contains("团员")) { model.ZhengZhi = 2; } else if (zz.Contains("群众")) { model.ZhengZhi = 3; } else if (zz.Contains("党员")) { model.ZhengZhi = 1; } // 小高考成绩 model.S_WuLi = sht.GetRow(rowIndex).GetCell(cou[i]) != null ? sht.GetRow(rowIndex).GetCell(cou[i]).ToString() : "无"; i++; model.S_HuaXue = sht.GetRow(rowIndex).GetCell(cou[i]) != null ? sht.GetRow(rowIndex).GetCell(cou[i]).ToString() : "无"; i++; model.S_LiShi = sht.GetRow(rowIndex).GetCell(cou[i]) != null ? sht.GetRow(rowIndex).GetCell(cou[i]).ToString() : "无"; i++; model.S_DiLi = sht.GetRow(rowIndex).GetCell(cou[i]) != null ? sht.GetRow(rowIndex).GetCell(cou[i]).ToString() : "无"; i++; model.S_ZhengZhi = sht.GetRow(rowIndex).GetCell(cou[i]) != null ? sht.GetRow(rowIndex).GetCell(cou[i]).ToString() : "无"; i++; model.S_ShengWu = sht.GetRow(rowIndex).GetCell(cou[i]) != null ? sht.GetRow(rowIndex).GetCell(cou[i]).ToString() : "无"; i++; model.S_XinXi = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); models.Add(model); // 志愿部分 Zmodel.IdNumber = model.IdNumber; Zmodel.ZhiYuan1 = sht.GetRow(rowIndex).GetCell(cou[i]) == null ? "0" : sht.GetRow(rowIndex).GetCell(cou[i]).ToString(); i++; Zmodel.ZhiYuan2 = sht.GetRow(rowIndex).GetCell(cou[i]) == null ? "0" : sht.GetRow(rowIndex).GetCell(cou[i]).ToString(); i++; Zmodel.ZhiYuan3 = sht.GetRow(rowIndex).GetCell(cou[i]) == null ? "0" : sht.GetRow(rowIndex).GetCell(cou[i]).ToString(); i++; Zmodel.ZhiYuan4 = sht.GetRow(rowIndex).GetCell(cou[i]) == null ? "0" : sht.GetRow(rowIndex).GetCell(cou[i]).ToString(); i++; Zmodel.ZhiYuan5 = sht.GetRow(rowIndex).GetCell(cou[i]) == null ? "0" : sht.GetRow(rowIndex).GetCell(cou[i]).ToString(); i++; Zmodel.ZhiYuan6 = sht.GetRow(rowIndex).GetCell(cou[i]) == null ? "0" : sht.GetRow(rowIndex).GetCell(cou[i]).ToString(); i++; Zmodel.FuCong = sht.GetRow(rowIndex).GetCell(cou[i++]).ToString(); Zmodels.Add(Zmodel); } if (StudentInfoManage.DaoRuStu(models) && ZhiYuanManage.DaoRu(Zmodels)) { Models.ExcelHelper.DeleteFile(path); return "<script>alert('信息导入成功!');window.history.go(-1);</script>"; } else { Models.ExcelHelper.DeleteFile(path); return "<script>alert('信息导入失败!');window.history.go(-1);</script>"; } } ``` 好,先溜了。 #### 最近比较忙。。。 ### END 上一篇:Eclipse下载付费音乐 下一篇:基于局域网的即时通信 文章评论 [ 聊聊技术 聊聊自己 ] 在巴甫洛夫条件反射 试验中:给定一条狗,每次摇铃后喂食,足够次数后,狗则听到铃声将会习惯性的分泌唾液,由此引发对铃声的依恋。延伸到实际,给定一个喜欢的妹子,每次见面赠与巴甫洛夫式 的礼品或者零食,由此引发妹子的依恋。引入薛定谔的猫 理论,在未表白前,妹子与自己一直处于一种“概率云”的状态,一旦表白则“概率云”将消失成为实际。在 巴甫洛夫式 后且未表白前,自己与妹子的关系为“既是恋人又不是恋人”的矛盾体。返回巴甫洛夫式 试验中,在妹纸形成足够的依恋过后,则可以打破薛定谔 “概率云”的状态。这个谜一样的自己,这一刻 薛定谔 附体,带着量子论般深沉的哀愁,让她从此不能自拔! 自此创作 巴甫洛夫薛定谔把妹法,深藏功与名。