日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

EasyOffice-.NetCore一行代码导入导出Excel,生成Word

發布時間:2023/12/4 asp.net 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 EasyOffice-.NetCore一行代码导入导出Excel,生成Word 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Excel和Word操作在開發過程中經常需要使用,這類工作不涉及到核心業務,但又往往不可缺少。以往的開發方式在業務代碼中直接引入NPOI、Aspose或者其他第三方庫,工作繁瑣,耗時多,擴展性差——比如基礎庫由NPOI修改為EPPlus,意味著業務代碼需要全部修改。由于工作需要,我在之前版本的基礎上,封裝了OfficeService,目的是最大化節省導入導出這種非核心功能開發時間,專注于業務實現,并且業務端與底層基礎組件完全解耦,即業務端完全不需要知道底層使用的是什么基礎庫,使得重構代價大大降低。

EasyOffice提供了

  • Excel導入:通過對模板類標記特性自動校驗數據(后期計劃支持FluentApi,即傳參決定校驗行為),并將有效數據轉換為指定類型,業務端只在拿到正確和錯誤數據后決定如何處理;

  • Excel導出:通過對模板類標記特性自動渲染樣式(后期計劃支持FluentApi,即傳參決定導出行為);

  • Word根據模板生成:支持使用文本和圖片替換,占位符只需定義模板類,制作Word模板,一行代碼導出docx文檔(后期計劃支持轉換為pdf);

  • Word根據Table母版生成:只需定義模板類,制作表格模板,傳入數據,服務會根據數據條數自動復制表格母版,并填充數據;

  • Word從空白創建等功能:特別復雜的Word導出任務,支持從空白創建;

EasyOffice底層庫目前使用NPOI,因此是完全免費的。
通過IExcelImportProvider等Provider接口實現了底層庫與實現的解耦,后期如果需要切換比如Excel導入的基礎庫為EPPlus,只需要提供IExcelImportProvider接口的EPPlus實現,并且修改依賴注入代碼即可。

提供了.net core自帶ServiceCollection注入和Autofac注入


builder.AddOffice(new OfficeOptions());


services.AddOffice(new OfficeOptions());

定義Excel模板類

public class Car
{

[ColName("車牌號")]
[Required]
[Regex(RegexConstant.CAR_CODE_REGEX)]
[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,
DataRowStartIndex = 1,
HeaderRowIndex = 0,
MappingDictionary = null,
SheetIndex = 0,
ValidateMode = ValidateModeEnum.Continue
}).Result;


var errorDatas = _rows.Where(x => !x.IsValid);



var validDatas = _rows.Where(x=>x.IsValid).FastConvert<ExcelCarTemplateDTO>();

轉換為DataTable

var dt = _excelImportService.ToTableAsync<ExcelCarTemplateDTO>
(
fileUrl,
0,
0,
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; }

導出Excel

var bytes = await _excelExportService.ExportAsync(new ExportOption<ExcelCarTemplateDTO>()
{
Data = list,
DataRowStartIndex = 1,
ExcelType = Bayantu.Extensions.Office.Enums.ExcelTypeEnum.XLS,
HeaderRowIndex = 0,
SheetName = "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);

CreateFromTemplateAsync - 根據模板生成Word


public class WordCarTemplateDTO
{

public string OwnerName { get; set; }

[Placeholder("{Car_Type Car Type}")]
public string CarType { get; set; }


public IEnumerable<Picture> CarPictures { get; set; }

public Picture CarLicense { get; set; }
}




string templateUrl = @"c:\template.docx";
WordCarTemplateDTO car = new WordCarTemplateDTO()
{
OwnerName = "劉德華",
CarType = "豪華型賓利",
CarPictures = new List<Picture>() {
new Picture()
{
PictureUrl = pic1,
FileName = "圖片1",
Height = 10,
Width = 3,
PictureData = null,
PictureType = PictureTypeEnum.JPEG
},
new Picture(){
PictureUrl = pic2
}
},
CarLicense = new Picture { PictureUrl = pic3 }
};

var word = await _wordExportService.CreateFromTemplateAsync(templateUrl, car);

File.WriteAllBytes(@"c:\file.docx", word.WordBytes);

CreateWordFromMasterTable-根據模板表格循環生成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);

CreateWordAsync - 從空白生成word

[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,
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);
}

github地址:https://github.com/holdengong/EasyOffice

水平有限,如果有bug歡迎提issue;如果本項目對您略有幫助,請幫忙Start和推薦,謝謝。

原文地址:https://www.cnblogs.com/holdengong/p/10889838.html

.NET社區新聞,深度好文,歡迎訪問公眾號文章匯總?http://www.csharpkit.com?

總結

以上是生活随笔為你收集整理的EasyOffice-.NetCore一行代码导入导出Excel,生成Word的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。