Excel和Word操做在开发过程当中常常须要使用,这类工做不涉及到核心业务,但又每每不可缺乏。以往的开发方式在业务代码中直接引入NPOI、Aspose或者其余第三方库,工做繁琐,耗时多,扩展性差——好比基础库由NPOI修改成EPPlus,意味着业务代码须要所有修改。因为工做须要,我在以前版本的基础上,封装了OfficeService,目的是最大化节省导入导出这种非核心功能开发时间,专一于业务实现,而且业务端与底层基础组件彻底解耦,即业务端彻底不须要知道底层使用的是什么基础库,使得重构代价大大下降。html
EasyOffice提供了前端
EasyOffice底层库目前使用NPOI,所以是彻底免费的。
经过IExcelImportProvider等Provider接口实现了底层库与实现的解耦,后期若是须要切换好比Excel导入的基础库为EPPlus,只须要提供IExcelImportProvider接口的EPPlus实现,而且修改依赖注入代码便可。
。git
支持.net core自带依赖注入github
// 注入Office基础服务 services.AddEasyOffice(new OfficeOptions());
public class Car { [ColName("车牌号")] //对应Excel列名 [Required] //校验必填 [Regex(RegexConstant.CAR_CODE_REGEX)] //正则表达式校验,RegexConstant预置了一些经常使用的正则表达式,也能够自定义 [Duplication] //校验模板类该列数据是否重复 public string CarCode { get; set; } [ColName("手机号")] [Regex(RegexConstant.MOBILE_CHINA_REGEX)] public string Mobile { get; set; } [ColName("身份证号")] [Regex(RegexConstant.IDENTITY_NUMBER_REGEX)] public string IdentityNumber { get; set; } [ColName("姓名")] [MaxLength(10)] //最大长度校验 public string Name { get; set; } [ColName("性别")] [Regex(RegexConstant.GENDER_REGEX)] public GenderEnum Gender { get; set; } [ColName("注册日期")] [DateTime] //日期校验 public DateTime RegisterDate { get; set; } [ColName("年龄")] [Range(0, 150)] //数值范围校验 public int Age { get; set; } }
var _rows = _excelImportService.ValidateAsync<ExcelCarTemplateDTO>(new ImportOption() { FileUrl = fileUrl, //Excel文件绝对地址 DataRowStartIndex = 1, //数据起始行索引,默认1第二行 HeaderRowIndex = 0, //表头起始行索引,默认0第一行 MappingDictionary = null, //映射字典,能够将模板类与Excel列从新映射, 默认null SheetIndex = 0, //页面索引,默认0第一个页签 ValidateMode = ValidateModeEnum.Continue //校验模式,默认StopOnFirstFailure校验错误后此行中止继续校验,Continue:校验错误后继续校验 }).Result; //获得错误行 var errorDatas = _rows.Where(x => !x.IsValid); //错误行业务处理 //将有效数据行转换为指定类型 var validDatas = _rows.Where(x=>x.IsValid).FastConvert<ExcelCarTemplateDTO>(); //正确数据业务处理
var dt = _excelImportService.ToTableAsync<ExcelCarTemplateDTO> //模板类型 ( fileUrl, //文件绝对地址 0, //页签索引,默认0 0, //表头行索引,默认0 1, //数据行索引,默认1 -1); //读取多少条数据,默认-1所有
[Header(Color = ColorEnum.BRIGHT_GREEN, FontSize = 22, IsBold = true)] //表头样式 [WrapText] //自动换行 public class ExcelCarTemplateDTO { [ColName("车牌号")] [MergeCols] //相同数据自动合并单元格 public string CarCode { get; set; } [ColName("手机号")] public string Mobile { get; set; } [ColName("身份证号")] public string IdentityNumber { get; set; } [ColName("姓名")] public string Name { get; set; } [ColName("性别")] public GenderEnum Gender { get; set; } [ColName("注册日期")] public DateTime RegisterDate { get; set; } [ColName("年龄")] public int Age { get; set; }
var bytes = await _excelExportService.ExportAsync(new ExportOption<ExcelCarTemplateDTO>() { Data = list, DataRowStartIndex = 1, //数据行起始索引,默认1 ExcelType = Bayantu.Extensions.Office.Enums.ExcelTypeEnum.XLS,//导出Excel类型,默认xls HeaderRowIndex = 0, //表头行索引,默认0 SheetName = "sheet1" //页签名称,默认sheet1 }); File.WriteAllBytes(@"c:\test.xls", bytes);
首先定义模板类,参考通用Excel导入正则表达式
//获取默认导入模板 var templateBytes = await _excelImportSolutionService.GetImportTemplateAsync<DemoTemplateDTO>(); //获取导入配置 var importConfig = await _excelImportSolutionService.GetImportConfigAsync<DemoTemplateDTO>("uploadUrl","templateUrl"); //获取预览数据 var previewData = await _excelImportSolutionService.GetFileHeadersAndRowsAsync<DemoTemplateDTO>("fileUrl"); //导入 var importOption = new ImportOption() { FileUrl = "fileUrl", ValidateMode = ValidateModeEnum.Continue }; object importSetData = new object(); //前端传过来的映射数据 var importResult = await _excelImportSolutionService.ImportAsync<DemoTemplateDTO> (importOption , importSetData , BusinessAction //业务方法委托 , CustomValidate //自定义校验委托 ); //获取导入错误消息 var errorMsg = await _excelImportSolutionService.ExportErrorMsgAsync(importResult.Tag);
//step1 - 定义模板类 public class WordCarTemplateDTO { //默认占位符为{PropertyName} public string OwnerName { get; set; } [Placeholder("{Car_Type Car Type}")] //重写占位符 public string CarType { get; set; } //使用Picture或IEnumerable<Picture>类型能够将占位符替换为图片 public IEnumerable<Picture> CarPictures { get; set; } public Picture CarLicense { get; set; } } //step2 - 制做word模板 //step3 - 导出word string templateUrl = @"c:\template.docx"; WordCarTemplateDTO car = new WordCarTemplateDTO() { OwnerName = "刘德华", CarType = "豪华型宾利", CarPictures = new List<Picture>() { new Picture() { PictureUrl = pic1, //图片绝对地址,若是设置了PictureData此项不生效 FileName = "图片1",//文件名称 Height = 10,//图片高度单位厘米默认8 Width = 3,//图片宽度单位厘米默认14 PictureData = null,//图片流数据,优先取这里的数据,没有则取url PictureType = PictureTypeEnum.JPEG //图片类型,默认jpeg }, new Picture(){ PictureUrl = pic2 } }, CarLicense = new Picture { PictureUrl = pic3 } }; var word = await _wordExportService.CreateFromTemplateAsync(templateUrl, car); File.WriteAllBytes(@"c:\file.docx", word.WordBytes);
//step1 - 定义模板类,参考上面 //step2 - 定义word模板,制做一个表格,填好占位符。 //step3 - 调用,以下示例,最终生成的word有两个用户表格 string templateurl = @"c:\template.docx"; var user1 = new UserInfoDTO() { Name = "张三", Age = 15, Gender = "男", Remarks = "简介简介" }; var user2 = new UserInfoDTO() { Name = "李四", Age = 20, Gender = "女", Remarks = "简介简介简介" }; var datas = new List<UserInfoDTO>() { user1, user2 }; for (int i = 0; i < 10; i++) { datas.Add(user1); datas.Add(user2); } var word = await _wordExportService.CreateFromMasterTableAsync(templateurl, datas); File.WriteAllBytes(@"c:\file.docx", word.WordBytes);
[Fact] public async Task 导出全部日程() { //准备数据 var date1 = new ScheduleDate() { DateTimeStr = "2019年5月5日 星期八", Addresses = new List<Address>() }; var address1 = new Address() { Name = "会场一", Categories = new List<Category>() }; var cate1 = new Category() { Name = "分类1", Schedules = new List<Schedule>() }; var schedule1 = new Schedule() { Name = "日程1", TimeString = "上午9:00 - 上午12:00", Speakers = new List<Speaker>() }; var schedule2 = new Schedule() { Name = "日程2", TimeString = "下午13:00 - 下午14:00", Speakers = new List<Speaker>() }; var speaker1 = new Speaker() { Name = "张三", Position = "总经理" }; var speaker2 = new Speaker() { Name = "李四", Position = "副总经理" }; schedule1.Speakers.Add(speaker1); schedule1.Speakers.Add(speaker2); cate1.Schedules.Add(schedule1); cate1.Schedules.Add(schedule2); address1.Categories.Add(cate1); date1.Addresses.Add(address1); var dates = new List<ScheduleDate>() { date1,date1,date1 }; var tables = new List<Table>(); //新建一个表格 var table = new Table() { Rows = new List<TableRow>() }; foreach (var date in dates) { //新建一行 var rowDate = new TableRow() { Cells = new List<TableCell>() }; //新增单元格 rowDate.Cells.Add(new TableCell() { Color = "lightblue", //设置单元格颜色 Paragraphs = new List<Paragraph>() { //新增段落 new Paragraph() { //段落里面新增文本域 Run = new Run() { Text = date.DateTimeStr,//文本域文本,Run还能够 Color = "red", //设置文本颜色 FontFamily = "微软雅黑",//设置文本字体 FontSize = 12,//设置文本字号 IsBold = true,//是否粗体 Pictures = new List<Picture>()//也能够插入图片 }, Alignment = Alignment.CENTER //段落居中 } } }); table.Rows.Add(rowDate); //会场 foreach (var addr in date.Addresses) { //分类 foreach (var cate in addr.Categories) { var rowCate = new TableRow() { Cells = new List<TableCell>() }; //会场名称 rowCate.Cells.Add(new TableCell() { Paragraphs = new List<Paragraph>{ new Paragraph() { Run = new Run() { Text = addr.Name, } } } }); rowCate.Cells.Add(new TableCell() { Paragraphs = new List<Paragraph>(){ new Paragraph() { Run = new Run() { Text = cate.Name, } } } }); table.Rows.Add(rowCate); //日程 foreach (var sche in cate.Schedules) { var rowSche = new TableRow() { Cells = new List<TableCell>() }; var scheCell = new TableCell() { Paragraphs = new List<Paragraph>() { new Paragraph() { Run = new Run() { Text = sche.Name } }, { new Paragraph() { Run = new Run() { Text = sche.TimeString } } } } }; foreach (var speaker in sche.Speakers) { scheCell.Paragraphs.Add(new Paragraph() { Run = new Run() { Text = $"{speaker.Position}:{speaker.Name}" } }); } rowSche.Cells.Add(scheCell); table.Rows.Add(rowSche); } } } } tables.Add(table); var word = await _wordExportService.CreateWordAsync(tables); File.WriteAllBytes(fileUrl, word.WordBytes); }
支持docx文件转换为html,或者pdf。底层库使用OpenXml和DinkToPdf,开源免费。若是大家公司没有Aspose.Word的Lisence,这是个能够考虑的选择。app
step1: Startup注入 serviceCollection.AddEasyOfficeExtensions(); step2: 构造函数注入IWordConverter _wordConverter step3:调用 var pdfBytes = _wordConverter.ConvertToPDF(docxBytes, "text");
https://github.com/holdengong/EasyOfficeasync