用openxml 生成Excel:

private void GenerateExcelUsingOpenxml(DataTable dataTable, string GeneratePath)
        {
            using (var workbook = SpreadsheetDocument.Create(GeneratePath, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();
                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
                InitializeStyleSheet(workbookPart);
                uint sheetId = 1;
                var excelColumns = new DocumentFormat.OpenXml.Spreadsheet.Columns();
                excelColumns.Append(CreateColumnData(1, Convert.ToUInt16(dataTable.Columns.Count + 1), 20));
                var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(excelColumns, sheetData);
                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                {
                    sheetId = sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                }
                DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetId.ToString() };
                sheets.Append(sheet);
                DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                List<String> columns = new List<string>();
                foreach (DataColumn column in dataTable.Columns)
                {
                    columns.Add(column.ColumnName);
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                    cell.StyleIndex = 0U;
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                    headerRow.AppendChild(cell);
                }
                sheetData.AppendChild(headerRow);
                foreach (DataRow dsrow in dataTable.Rows)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                    foreach (String col in columns)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                        cell.StyleIndex = 0U;
                        newRow.AppendChild(cell);
                    }

sheetData.AppendChild(newRow);
                }
                workbook.Close();
            }
        }

用Openxml 做mailmerge:

生成组合模板:public DataTable GenerateGroupTeamplates(DataTable DT)
        {           
            //Add a dictinary type collection            
            Dictionary<string, int> TemplatePageCollection = new Dictionary<string, int> { };
            IEnumerable<string> TemplateGroups = ConnectTemplateAndGroup_new(DT);
            DataTable CustomerAndTempInfoDT = AddColumnForCustomerAndTempInfo(DT);   
           
            string MergedGroupTemplatesPath = SMConfig.MergedGroupTemplatePath;
            string TemplateCopiedFolder =SMConfig.TempleFolderPath;
            string SystemTemplatePath = SMConfig.TemplatePath;
            DataTable TemplateCollection = GetTemplateInformation();
            foreach (string TeamplateString in TemplateGroups)
            {
                int PageCount = 0;
                string[] temps = TeamplateString.Split(',');               
                for (int i = 0; i < temps.Length; i++)
                {
                    string OneTeampName = SystemTemplatePath + "\\" + TemplateCollection.Select("TemplateIndex='" + temps[i] + "'")[0]["TemplateName"].ToString();//Rows[indexRow]["TemplateName"].ToString();           
                    File.Copy(OneTeampName, TemplateCopiedFolder + "\\" + temps[i]+ ".docx", true);
                }
                string ConnectFile = TemplateCopiedFolder + "\\" + temps[0] + ".docx";                
                for (int i = 1; i < temps.Length; i++)
                {
                    string RecursiveFile = TemplateCopiedFolder + "\\" + temps[i] + ".docx";
                    using (WordprocessingDocument myDoc = WordprocessingDocument.Open(ConnectFile, true))
                    {
                        try
                        {
                            MainDocumentPart mainPart = myDoc.MainDocumentPart;
                            Paragraph SectionPageBreakParagraph = new Paragraph(new ParagraphProperties(new SectionProperties(new SectionType() { Val = SectionMarkValues.NextPage })));
                            Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page }));
                            mainPart.Document.Body.Append(PageBreakParagraph);//此处添加空白页   
                            mainPart.Document.Body.Append(SectionPageBreakParagraph);//add section breakparagraph
                            string altChunkId = "AltChunkId0" + i;
                            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                            AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                            using (FileStream fileStream = File.Open(RecursiveFile, FileMode.Open))
                            {
                                chunk.FeedData(fileStream);
                                fileStream.Close();
                            }
                            AltChunk altChunk = new AltChunk();
                            altChunk.Id = altChunkId;
                            using (WordprocessingDocument tempFileDoc = WordprocessingDocument.Open(RecursiveFile, true))
                            {
                                PageCount = CountPage(PageCount, tempFileDoc);
                                IEnumerable<SectionProperties> sectionProperties = tempFileDoc.MainDocumentPart.Document.Body.Elements<SectionProperties>();
                                mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
                                mainPart.Document.Body.Last().Append(sectionProperties.FirstOrDefault().CloneNode(true));
                                mainPart.Document.Save();
                                myDoc.Close();
                                tempFileDoc.Close();
                            }
                        }
                        catch (Exception ex) { }
                    }
                }
                string GroupFilePath = MergedGroupTemplatesPath + "\\" + TeamplateString + ".docx";
                File.Copy(ConnectFile, GroupFilePath, true);  
                string[] CopiedFiles = Directory.GetFiles(TemplateCopiedFolder);
                for (int deleInd = 0; deleInd < CopiedFiles.Length; deleInd++)
                {
                    File.Delete(CopiedFiles[deleInd]);
                }               
                TemplatePageCollection.Add(new FileInfo(GroupFilePath).Name, PageCount+2);
            }
            //装载Page到DataTable
            foreach (DataRow row in CustomerAndTempInfoDT.Rows)
            {
                row["Pages"] = TemplatePageCollection[row["GroupTemplateName"].ToString()];  
            }
            return CustomerAndTempInfoDT;
        }

Do Merge:

private void DoMerge(GeneratePara Param, string Path, string[] files)
        {
            for (int i = 0; i < files.Length; i++)
            {
                string uniqueFileName = string.Format("{0}Part{1}.docx", Path, i);
                File.Copy(files[i], uniqueFileName, true);
                DataRow[] drs = Param.SourceExcel.Select(String.Format("GroupTemplateName = '{0}'", new FileInfo(files[i]).Name));
                CalculateSubPartPages.Add(string.Format("Part{0}.docx", i),Convert.ToInt32(drs[0]["Pages"])*(drs.Count()));
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(uniqueFileName, true), doc = WordprocessingDocument.Open(files[i], true))
                {                    
                    XElement body = XElement.Parse(wordDocument.MainDocumentPart.Document.Body.OuterXml);
                    wordDocument.MainDocumentPart.Document.RemoveAllChildren();
                    wordDocument.MainDocumentPart.Document.AppendChild<Body>(new Body());
                    foreach (DataRow row in drs)
                    {
                        try
                        {
                            BindCalculateCustomerPart(i, row);
                            DataRow Row = Param.SourceData.Select("customer_no='" + row.ItemArray[0].ToString().PadLeft(9, '0') + "'")[0];
                            XElement newBody = XElement.Parse(doc.MainDocumentPart.Document.Body.OuterXml);
                            IList<XElement> mailMergeFields =
                          (from el in newBody.Descendants()
                           where ((el.Name == (XMLNS + "t") && el.Value != null && el.Value.Contains("«") && el.Value.Contains("»")))
                           select el).ToList();
                            string fieldName = string.Empty;
                            XElement newElement = null;
                            foreach (XElement field in mailMergeFields)
                            {
                                fieldName = field.Value.Replace("«", "").Replace("»", "").Replace("-", "_");
                                if (Row.Table.Columns.Contains(fieldName))
                                {
                                    if (Row[fieldName] == DBNull.Value)
                                        Row[fieldName] = string.Empty;
                                    newElement = field;
                                    newElement.Value = Regex.Replace(Row.Field<string>(fieldName).Trim(), "\\s+", " ", RegexOptions.IgnoreCase);
                                    field.ReplaceWith(newElement);
                                }
                            }
                            Body bo = new Body(newBody.ToString());
                            wordDocument.MainDocumentPart.Document.Body.AppendChild<Body>(bo);                                                        
                            IEnumerable<SectionProperties> sectionProperties = doc.MainDocumentPart.Document.Body.Elements<SectionProperties>();
                            wordDocument.MainDocumentPart.Document.Body.Last().Append(sectionProperties.FirstOrDefault().CloneNode(true));
                            Paragraph PageBreakParagraph = new Paragraph(new ParagraphProperties(new SectionProperties(new SectionType() { Val = SectionMarkValues.EvenPage })));
                            wordDocument.MainDocumentPart.Document.Body.Append(PageBreakParagraph);//此处添加空白页
                        }
                        catch (Exception ex)
                        {
                            BindErrorCustomerNoDT(row.ItemArray[0].ToString());
                            continue;
                        }
                    }
                    wordDocument.MainDocumentPart.Document.Save();
                    wordDocument.Close();
                }
            }
        }

转载于:https://www.cnblogs.com/special-tao/p/4333017.html

Openxml 笔记相关推荐

  1. VSTO学习笔记(二)Excel对象模型

    原文:VSTO学习笔记(二)Excel对象模型 上一次主要学习了VSTO的发展历史及其历代版本的新特性,概述了VSTO对开发人员的帮助和效率提升.从这次开始,将从VSTO 4.0开始,逐一探讨VSTO ...

  2. (一)JAVA基于OPENXML的word文档插入、合并、替换操作系列之基础篇

    (一)JAVA基于OPENXML的word文档插入.合并.替换操作系列之基础篇 前言 什么是Open Xml? Open XML SDK 这系列笔记要做点什么? 涉及技术点 关于word.openxm ...

  3. C# dotnet 使用 OpenXml 解析 PPT 元素的坐标和宽度高度

    在阅读本文之前,我期望你能了解基础的 PPT 解析内容,或看我的入门级博客.本文将告诉大家如何从 PPT 里面解析出通用元素的 x 和 y 的值,以及元素的宽度和高度的值 在开始之前请看 C# dot ...

  4. (五)、JAVA基于OPENXML的word文档插入、合并、替换操作系列之word文件合并[支持多文件]

    (五).JAVA基于OPENXML的word文档插入.合并.替换操作系列之word文件合并[支持多文件] 二.word合并的多种方案简单比较 三.基于Open Xml WordprocessingML ...

  5. java openxml 操作 word,(三)、JAVA基于OPENXML的word文档插入、合并、替换操作系列之html转word...

    (三).JAVA基于OPENXML的word文档插入.合并.替换操作系列之html转word 系列笔记传送门 富文本转word文档 准备待转换内容 内容清理与格式化 转换成word文档 输出结果展示 ...

  6. onethink入门笔记(一)

    onethink入门笔记(一) 由于公司需求所以大概花了一个星期搞了一个一个基于onethink的数据管理平台demo不得不说onethink这个基于thinkphp3.2.3的框架还是很棒的 让我这 ...

  7. 【VS开发】VSTO 学习笔记(十)Office 2010 Ribbon开发

    微软的Office系列办公套件从Office 2007开始首次引入了Ribbon导航菜单模式,其将一系列相关的功能集成在一个个Ribbon中,便于集中管理.操作.这种Ribbon是高度可定制的,用户可 ...

  8. 【读书笔记】知易行难,多实践

    前言: 其实,我不喜欢看书,只是喜欢找答案,想通过专业的解答来解决我生活的困惑.所以,我听了很多书,也看了很多书,但看完书,没有很多的实践,导致我并不很深入在很多时候. 分享读书笔记: <高效1 ...

  9. 【运维学习笔记】生命不息,搞事开始。。。

    001生命不息,搞事不止!!! 这段时间和hexesdesu搞了很多事情! 之前是机械硬盘和固态硬盘的测速,我就在那默默的看着他一个硬盘一个机械测来测去. 坐在他后面,每天都能看到这位萌萌的小男孩,各 ...

  10. SSAN 关系抽取 论文笔记

    20210621 https://zhuanlan.zhihu.com/p/353183322 [KG笔记]八.文档级(Document Level)关系抽取任务 共指id嵌入一样 但是实体嵌入的时候 ...

最新文章

  1. 动手写一个Remoting接口测试工具(附源码下载)
  2. oracle 如何筛选重复,求sql--筛选A字段相同,B字段不同且不重复的记录
  3. IntelliJ IDEA for Mac工件包(artifact)中 Web facet resources 的模块名称有误,如何修改?
  4. 05_JS流程控制语句
  5. 大数据相关技术说明(一)
  6. sklearn adaboost_集成学习-从零推导和实现adaboost与3D可视化
  7. 同一个html自动跳转分页,一个页面有多个分页,相互影响
  8. 海思加鸿蒙的零距离思考,自主生态之路在何方
  9. Go语言实现并行分段求和计算
  10. 微信 8.0 来啦,炸裂!
  11. 数据库增删改查工具类 以及C3P0开源的JDBC连接池操作
  12. qq截图和ps相结合的功能
  13. JavaScript高级程序设计学习笔记(一)
  14. 调剂深圳大学计算机技术,深圳大学:2020年硕士研究生招生调剂办法公告
  15. JAVA学习(三)----常量和数据类型
  16. 饥荒 Don‘t Starve Together Mac游戏介绍
  17. php Guzzle源码,PHP Guzzle获取请求
  18. 关于TopoJSON以及制作方法
  19. 如何从Gitlab上拉取代码
  20. 仓库温度湿度控制措施_仓库温湿度管理规定_仓库温湿度监测管理制度

热门文章

  1. 字体测试打分软件哪个好,准确率奇高的看图识字体网站-在线认字体
  2. 华为手机安装Google Play教程
  3. 【转】深入浅出的讲解傅里叶变换(真正的通俗易懂)
  4. flutter混编ios打包生成ipa文件
  5. CAD:AutoCAD快捷键指令大全(非常值得收藏),本人项目案例实践积累总结
  6. R如何读取txt文件
  7. 西门子PLC S7-200数字量扩展模块
  8. 如何在ppt全屏演示时仍然显示任务栏?
  9. 数学常用特殊符号读音
  10. 有道翻译API接口的服务开通与使用Python进行接口调用实例演示,有道智云·AI开放平台