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