C#中word导出功能骚操作

将没用的东西全部去掉,修改Index.cshtml页面成这样:

复制代码
1 @{
2 ViewBag.Title = “Home Page”;
3 }
4


5 @

ASP.NET

@
6 <input type=“button” value=“导出” οnclick=“location.href = ‘@Url.Action(“GetExport”,“Home”)’” />
7

复制代码
在 HomeController 中创建:GetExport

创建一个类ExportFileOperator(所有的word操作),此类需要继承Controller,因为有返回File操作方法

1、 在GetExport中首先命名一个导出word标题就叫:测试导出Word文件

string title = “测试导出Word文件”;
创建doc:

var doc = ExportFileOperator.CreateBuilder(“GroupForm.doc”);
2、CreateBuilder方法实现为(此处操作需要Aspose.Word组件,是操作word的,这个需要大家自己去找一下,或者网上找个破解的):
复制代码
1 private static string _tempPath = AppDomain.CurrentDomain.BaseDirectory;
2 public static (Document doc, DocumentBuilder builder) CreateBuilder(string tempFileName)
3 {
4 string tempPath = $"{_tempPath}{tempFileName}";
5 Document doc = new Document(tempPath);
6 return (doc, new DocumentBuilder(doc));
7 }
复制代码
3、插入标题(需要在word中写一个标签,作为标题插入的地址):

最终可以显示结果为这样:

方法:

ExportFileOperator.InsertTitle(ref doc.Item2, title);//插入标题

public static void InsertTitle(ref DocumentBuilder builder, string fileName, string tempBookMarkName = “title”)
{
builder.MoveToBookmark(tempBookMarkName);
builder.Write(fileName);
}
4、根据业务实体,将实体数据写入到word中,也是核心所在

首先命名一个数据类:

View Code
其中重要的地方是:需要给每个字段一个Description,这里面的值对应的就是word模板中的名称,如下:

这里因为数据是保密的,我就将一些字段删除了,包括word模板中的一些也删除了,就拿出一部分。

和数据库交互的部分我也没写,就将查出来的数据先命名一个_enterpriseStr,最后用Newtonsoft转换成实体这样操作了哈:

EnterpriseEntity enterprise = JsonConvert.DeserializeObject(_enterpriseStr);

5、将查出来的数据,插入到word中,完成最终的导出:

1 ExportFileOperator.InsertFormData(enterprise, ref doc.Item1);//实体数据插入
2 return new ExportFileOperator().FileResult(title, doc.Item1);
其中最重要的方法就是InsertFormData这个,他的实现如下:

复制代码
1 public static void InsertFormData(T objFormData, ref Document document)
2 {
3 NodeCollection allTables = document.GetChildNodes(NodeType.Table, true);
4 List headDescribeNameList = GetObjectHeadDescription();//获取实体中每个Description中的值
5 foreach (Table tableFirst in allTables)
6 {
7 for (int headIndex = 0; headIndex < headDescribeNameList.Count; headIndex++)//循环实体中的每个DescribeName
8 {
9 for (int rowIndex = 0; rowIndex < tableFirst.Rows.Count; rowIndex++)//遍历word模板中所有的table
10 {
11 for (int cellIndex = 0; cellIndex < tableFirst.Rows[rowIndex].Cells.Count; cellIndex++)//遍历模板中所有的table每行的列数
12 {
13 if (tableFirst.Rows[rowIndex].Cells[cellIndex].GetText() != null && tableFirst.Rows[rowIndex].Cells[cellIndex].GetText().Contains(headDescribeNameList[headIndex]) &&
14 ((tableFirst.Rows[rowIndex].Cells.Count > cellIndex && tableFirst.Rows[rowIndex].Cells[cellIndex + 1] != null && tableFirst.Rows[rowIndex].Cells[cellIndex + 1].GetText().Equals("\a")) || (tableFirst.Rows.Count > rowIndex && tableFirst.Rows[rowIndex + 1] != null && tableFirst.Rows[rowIndex + 1].Cells[cellIndex] != null && tableFirst.Rows[rowIndex + 1].Cells[cellIndex].GetText().Equals("\a"))))//如果遍历的cell不为空、其中的值能和DescribeName匹配上,并且这个单元的右边的cell或者下边cell有占位,而且是空,就在此处插入值
15 {
16 var objValue = GetObjectValueByPropName(objFormData, headDescribeNameList[headIndex]);//根据DescribeName获取对应的值
17 if (tableFirst.Rows[rowIndex].Cells.Count > cellIndex && tableFirst.Rows[rowIndex].Cells[cellIndex + 1] != null && tableFirst.Rows[rowIndex].Cells[cellIndex + 1].GetText().Equals("\a"))
18 {
19 InsertCell(objValue, document, tableFirst.Rows[rowIndex].Cells[cellIndex + 1]);//优先在右变空位插入值
20 break;
21 }
22 InsertCell(objValue, document, tableFirst.Rows[rowIndex + 1].Cells[cellIndex]);//右侧如果没有就在下边空位插入值
23 break;
24 }
25 }
26 }
27 }
28 }
29 }
复制代码
复制代码
1 public static List GetObjectHeadDescription()
2 {
3 var obj = Activator.CreateInstance();
4 MethodInfo method = obj.GetType().GetMethod(“GetThisDescriptionName”, new Type[] { });//每个实体需要有GetThisDescriptionName这个方法
5 return (List)(method?.Invoke(obj, null));
6 }
复制代码
其中GetThisDescriptionName方法需求在每个实体类中有实现:

根据descriptionName获取实体中的值:

复制代码
1 private static string GetObjectValueByPropName(T objFormData, string descriptionName)
2 {
3 try
4 {
5 var properties = objFormData.GetType().GetProperties();
6 foreach (var propertyInfo in properties)
7 {
8 var descriptionAttributes = (DescriptionAttribute[])propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
9 if (descriptionAttributes.Length > 0 && !string.IsNullOrWhiteSpace(descriptionAttributes[0].Description) && descriptionAttributes[0].Description.Equals(descriptionName))
10 {
11 return propertyInfo.GetValue(objFormData) == null ? “无” : propertyInfo.GetValue(objFormData).ToString();
12 }
13 }
14 return “无”;
15 }
16 catch (Exception e)
17 {
18 Console.WriteLine(e);
19 throw;
20 }
21 }
复制代码
在cell中插入值:

复制代码
1 private static void InsertCell(string value, Document doc, Cell cell)
2 {
3 Cell insertCell = cell;
4 insertCell.FirstParagraph.Remove();
5 Paragraph p = new Paragraph(doc);
6 p.AppendChild(new Run(doc, (value == null ? “” : value)));
7 p.ParagraphFormat.Alignment = ParagraphAlignment.Center;
8 insertCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
9 insertCell.AppendChild§;
10 }
复制代码
最后一个方法FileResult:

复制代码
1 public FileResult FileResult(string fileName, Document doc)
2 {
3 var filePathName = $"{fileName}.doc";
4 doc.Save(Path.Combine(_tempPath, “temp”, filePathName), SaveFormat.Doc); //保存word
5 filePathName = Path.Combine(_tempPath, “temp”, filePathName);
6 return File(filePathName, “application/doc”, $"{fileName}.Doc");
7 }
复制代码
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn
深圳网站建设www.sz886.com

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值