.net framework导出Excel、Word、Pdf和Html:Magicodes.IE的简单使用
这里介绍一个很方便实用的库:Magicodes.IE,导入导出通用库,通过导入导出DTO模型来控制导入和导出,支持Excel、Word、Pdf和Html。
本篇介绍基本使用方法,使用方法非常简单,不需要学习npoi的应用。
在vs中,新建一个控制台项目(测试用,可以建其他项目,比如asp.net mvc ,winform都可以)
右键单击项目中的引用,选择nuget包管理,导入nuget包:这里只使用excel,所以只导入了Magicodes.IE.Excel
Magicodes.IE.Core
Magicodes.IE.Excel
Magicodes.IE.Pdf
Magicodes.IE.Word
Magicodes.IE.Html
1. 首先准备好一个类,这个类包含需要导出的属性一、导出数据
public class Question
{
public string Title { get; set; }
public string Content { get; set; }
public string Options { get; set; }
public string Answer { get; set; }
}
2.导出方法
这里如果new List<Question>()不设置数据,就可以直接导出Question的模板
static void ExportQuestion()
{
//这里需要补充,如果路径不存在要创建路径,否则会报错
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "question.xlsx");
var exporter = new ExcelExporter();
var result = exporter.Export(filePath, new List<Question>() {
new Question()
{
Title = "Question1",
Content = "Question content 1",
Options = "A:option1,B:option2,C:option3,D:option4",
Answer = "A",
},
new Question()
{
Title = "Question2",
Content = "Question content 2",
Options = "A:option11,B:option22,C:option33,D:option43",
Answer = "B",
}
});
}
其他方法参考下代码吧:
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Magicodes.ExporterAndImporter.Excel.Builder;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
//static void Main(string[] args)
static async Task Main(string[] args)
{
await Import3();
Console.WriteLine("Hello World!");
}
#region 导出excel demo
/// <summary>
/// 导出excel测试:excel1
/// </summary>
static void Demo1()
{
//这里需要补充,如果路径不存在要创建路径,否则会报错
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "demo1.xlsx");
var exporter = new ExcelExporter();
var result = exporter.Export(filePath, new List<ExportTestData>() {
new ExportTestData()
{
Name1 = "1",
Name2 = "test",
Name3 = "12",
Name4 = "11",
},
new ExportTestData()
{
Name1 = "1",
Name2 = "test",
Name3 = "12",
Name4 = "11",
}
});
}
static void ExportQuestion()
{
//这里需要补充,如果路径不存在要创建路径,否则会报错
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "question.xlsx");
var exporter = new ExcelExporter();
var result = exporter.Export(filePath, new List<Question>() {
new Question()
{
Title = "Question1",
Content = "Question content 1",
Options = "A:option1,B:option2,C:option3,D:option4",
Answer = "A",
},
new Question()
{
Title = "Question2",
Content = "Question content 2",
Options = "A:option11,B:option22,C:option33,D:option43",
Answer = "B",
}
});
}
/// <summary>
/// 导出空模板测试:excel11
/// </summary>
static void Demo11()
{
//这里需要补充,如果路径不存在要创建路径,否则会报错
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ImportProduct2Dto.xlsx");
var exporter = new ExcelExporter();
var result = exporter.Export(filePath, new List<ImportProduct2Dto>());
}
/// <summary>
/// 利用特性导出excel2
/// </summary>
static void Demo2()
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "demo2.xlsx");
ExcelExporter exporter = new ExcelExporter();
var result = exporter.Export(filePath, new List<ExportTestDataWithAttrs>()
{
new ExportTestDataWithAttrs()
{
Text1 = "啊实打实大苏打撒",
Name="aa",
Number =5000,
Text2 = "w萨达萨达萨达撒",
Text3 = "sadsad打发打发士大夫的"
},
new ExportTestDataWithAttrs()
{
Text1 = "啊实打实大苏打撒",
Name="啊实打实大苏打撒",
Number =6000,
Text2 = "w萨达萨达萨达撒",
Text3 = "sadsad打发打发士大夫的"
},
new ExportTestDataWithAttrs()
{
Text1 = "啊实打实速度大苏打撒",
Name="萨达萨达",
Number =6000,
Text2 = "突然他也让他人",
Text3 = "sadsad打发打发士大夫的"
},
});
}
/// <summary>
/// 列头处理或者多语言支持测试
/// </summary>
static void Demo3()
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles","testAttrsLocalization.xlsx");
if (File.Exists(filePath)) File.Delete(filePath);
var exporter = new ExcelExporter();
ExcelBuilder.Create().WithColumnHeaderStringFunc((key) =>
{
if (key.Contains("文本"))
{
return "Text";
}
return "未知语言";
}).Build();
var result = exporter.Export(filePath, new List<AttrsLocalizationTestData>()
{
new AttrsLocalizationTestData()
{
Text = "啊实打实大苏打撒",
Name="aa",
Number =5000,
Text2 = "w萨达萨达萨达撒",
Text3 = "sadsad打发打发士大夫的"
},
new AttrsLocalizationTestData()
{
Text = "啊实打实大苏打撒",
Name="啊实打实大苏打撒",
Number =6000,
Text2 = "w萨达萨达萨达撒",
Text3 = "sadsad打发打发士大夫的"
},
new AttrsLocalizationTestData()
{
Text = "啊实打实速度大苏打撒",
Name="萨达萨达",
Number =6000,
Text2 = "突然他也让他人",
Text3 = "sadsad打发打发士大夫的"
},
});
}
#endregion
/// <summary>
/// 从excel导入数据测试1
/// </summary>
/// <returns></returns>
private static async Task Import1()
{
var importer = new ExcelImporter();
var importResult = await importer.Import<ImportProductDto>(Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "importer1.xlsx"));
foreach (var item in importResult.Data)
{
Console.WriteLine(item.Name+"-"+item.Code+"-"+item.BarCode);
}
}
/// <summary>
/// 导入带有枚举值的数据
/// </summary>
/// <returns></returns>
private static async Task Import2()
{
var importer = new ExcelImporter();
var importResult = await importer.Import<ImportProduct2Dto>(Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ImportProduct2Dto.xlsx"));
foreach (var item in importResult.Data)
{
Console.WriteLine(item.Name + "-" + item.Code + "-" + item.BarCode+"-"+item.Type.ToString());
}
}
/// <summary>
/// 导入数据验证
/// </summary>
/// <returns></returns>
private static async Task Import3()
{
var importer = new ExcelImporter();
var importResult = await importer.Import<ImportProduct3Dto>(Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ImportProduct2Dto.xlsx"));
if (importResult.HasError)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var item in importResult.RowErrors)
{
stringBuilder.AppendLine("出错行数:" + item.RowIndex);
foreach (var fielderror in item.FieldErrors)
{
stringBuilder.AppendLine("\t出错列:" + fielderror.Key+"\n\t出错原因:"+fielderror.Value);
}
}
Console.WriteLine(stringBuilder.ToString());
}
else
{
foreach (var item in importResult.Data)
{
Console.WriteLine(item.Name + "-" + item.Code + "-" + item.BarCode + "-" + item.Type.ToString());
}
}
}
}
#region 导出excel demo class
public class ExportTestData
{
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
public string Name4 { get; set; }
}
public class Question
{
public string Title { get; set; }
public string Content { get; set; }
public string Options { get; set; }
public string Answer { get; set; }
}
/// <summary>
/// 特性导出Excel
/// </summary>
[ExcelExporter(Name ="测试",TableStyle ="Light10")]
public class ExportTestDataWithAttrs
{
[ExporterHeader(DisplayName="加粗文本",IsBold=true)]
public string Text1 { get; set; }
[ExporterHeader(DisplayName ="普通文本")]
public string Text2 { get; set; }
[ExporterHeader(DisplayName = "忽略", IsIgnore = true)]
public string Text3 { get; set; }
[ExporterHeader(DisplayName = "数值", Format = "#,##0")]
public double Number { get; set; }
[ExporterHeader(DisplayName = "名称", IsAutoFit = true)]
public string Name { get; set; }
}
/// <summary>
/// 列头处理或者多语言支持
/// </summary>
[ExcelExporter(Name = "测试", TableStyle = "Light10")]
public class AttrsLocalizationTestData
{
[ExporterHeader(DisplayName = "加粗文本", IsBold = true)]
public string Text { get; set; }
[ExporterHeader(DisplayName = "普通文本")]
public string Text2 { get; set; }
[ExporterHeader(DisplayName = "忽略", IsIgnore = true)]
public string Text3 { get; set; }
[ExporterHeader(DisplayName = "数值", Format = "#,##0")]
public double Number { get; set; }
[ExporterHeader(DisplayName = "名称", IsAutoFit = true)]
public string Name { get; set; }
}
#endregion
/// <summary>
/// 从excel导入数据 dto
/// </summary>
public class ImportProductDto
{
/// <summary>
/// 产品名称
/// </summary>
[ImporterHeader(Name = "产品名称")]
public string Name { get; set; }
/// <summary>
/// 产品代码
/// </summary>
[ImporterHeader(Name = "产品代码")]
public string Code { get; set; }
/// <summary>
/// 产品条码
/// </summary>
[ImporterHeader(Name = "产品条码")]
public string BarCode { get; set; }
}
[ExcelExporter(Name = "测试1", TableStyle = "Light10")]
public class ImportProduct2Dto
{
/// <summary>
/// 产品名称
/// </summary>
[ImporterHeader(Name = "产品名称")]
[ExporterHeader(DisplayName = "产品名称")]
public string Name { get; set; }
/// <summary>
/// 产品代码
/// </summary>
[ImporterHeader(Name = "产品代码")]
[ExporterHeader(DisplayName = "产品代码")]
public string Code { get; set; }
/// <summary>
/// 产品条码
/// </summary>
[ImporterHeader(Name = "产品条码")]
[ExporterHeader(DisplayName = "产品条码")]
public string BarCode { get; set; }
/// <summary>
/// 客户Id
/// </summary>
[ImporterHeader(Name = "客户代码")]
[ExporterHeader(DisplayName = "客户代码")]
public long ClientId { get; set; }
/// <summary>
/// 产品型号
/// </summary>
[ImporterHeader(Name = "产品型号")]
[ExporterHeader(DisplayName = "产品型号")]
public string Model { get; set; }
/// <summary>
/// 申报价值
/// </summary>
[ImporterHeader(Name = "申报价值")]
[ExporterHeader(DisplayName = "申报价值")]
public double DeclareValue { get; set; }
/// <summary>
/// 货币单位
/// </summary>
[ImporterHeader(Name = "货币单位")]
[ExporterHeader(DisplayName = "货币单位")]
public string CurrencyUnit { get; set; }
/// <summary>
/// 品牌名称
/// </summary>
[ImporterHeader(Name = "品牌名称")]
[ExporterHeader(DisplayName = "品牌名称")]
public string BrandName { get; set; }
/// <summary>
/// 尺寸
/// </summary>
[ImporterHeader(Name = "尺寸(长x宽x高)")]
[ExporterHeader(DisplayName = "尺寸(长x宽x高)")]
public string Size { get; set; }
/// <summary>
/// 重量
/// </summary>
[ImporterHeader(Name = "重量(KG)")]
[ExporterHeader(DisplayName = "重量(KG)")]
public double Weight { get; set; }
/// <summary>
/// 类型
/// </summary>
[ImporterHeader(Name = "类型")]
[ExporterHeader(DisplayName = "类型")]
public ImporterProductType Type { get; set; }
/// <summary>
/// 是否行
/// </summary>
[ImporterHeader(Name = "是否行")]
[ExporterHeader(DisplayName = "是否行")]
public bool IsOk { get; set; }
}
public class ImportProduct3Dto
{
/// <summary>
/// 产品名称
/// </summary>
[ImporterHeader(Name = "产品名称", Description = "必填")]
[Required(ErrorMessage = "产品名称是必填的")]
public string Name { get; set; }
/// <summary>
/// 产品代码
/// </summary>
[ImporterHeader(Name = "产品代码", Description = "最大长度为8")]
[MaxLength(8, ErrorMessage = "产品代码最大长度为8")]
public string Code { get; set; }
/// <summary>
/// 产品条码
/// </summary>
[ImporterHeader(Name = "产品条码")]
[MaxLength(10, ErrorMessage = "产品条码最大长度为10")]
[RegularExpression(@"^\d*$", ErrorMessage = "产品条码只能是数字")]
public string BarCode { get; set; }
/// <summary>
/// 客户Id
/// </summary>
[ImporterHeader(Name = "客户代码")]
public long ClientId { get; set; }
/// <summary>
/// 产品型号
/// </summary>
[ImporterHeader(Name = "产品型号")]
public string Model { get; set; }
/// <summary>
/// 申报价值
/// </summary>
[ImporterHeader(Name = "申报价值")]
public double DeclareValue { get; set; }
/// <summary>
/// 货币单位
/// </summary>
[ImporterHeader(Name = "货币单位")]
public string CurrencyUnit { get; set; }
/// <summary>
/// 品牌名称
/// </summary>
[ImporterHeader(Name = "品牌名称")]
public string BrandName { get; set; }
/// <summary>
/// 尺寸
/// </summary>
[ImporterHeader(Name = "尺寸(长x宽x高)")]
public string Size { get; set; }
/// <summary>
/// 重量
/// </summary>
[ImporterHeader(Name = "重量(KG)")]
public double Weight { get; set; }
/// <summary>
/// 类型
/// </summary>
[ImporterHeader(Name = "类型")]
public ImporterProductType Type { get; set; }
/// <summary>
/// 是否行
/// </summary>
[ImporterHeader(Name = "是否行")]
public bool IsOk { get; set; }
}
public enum ImporterProductType
{
[Display(Name = "第一")]
One,
[Display(Name = "第二")]
Two
}
}