用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();
                }
            }
        }

Openxml 笔记的更多相关文章

  1. OpenXml SDK学习笔记(1):Word的基本结构

    能写多少篇我就不确定了,可能就这一篇就太监了,也有可能会写不少. OpenXml SDK 相信很多人都不陌生,这个就是管Office一家的文档格式,Word, Excel, PowerPoint等都用 ...

  2. OpenXml SDK学习笔记(4):设置文件级别的样式

    观察上一段日记最后的代码: 这里的样式基本可以理解为行内CSS.那么既然有行内的样式,就肯定有外部的样式.那这部分就对应笔记1里说的style.xml文件.这个文件对应的是Document.MainD ...

  3. VSTO 学习笔记(十)Office 2010 Ribbon开发

    原文:VSTO 学习笔记(十)Office 2010 Ribbon开发 微软的Office系列办公套件从Office 2007开始首次引入了Ribbon导航菜单模式,其将一系列相关的功能集成在一个个R ...

  4. VSTO学习笔记(九)浅谈Excel内容比较

    原文:VSTO学习笔记(九)浅谈Excel内容比较 说起文件内容比较,或许我们首先想到的是UltraCompare这类专业比较的软件,其功能非常强大,能够对基于文本的文件内容作出快速.准确的比较,有详 ...

  5. VSTO学习笔记(七)基于WPF的Excel分析、转换小程序

    原文:VSTO学习笔记(七)基于WPF的Excel分析.转换小程序 近期因为工作的需要,要批量处理Excel文件,于是写了一个小程序,来提升工作效率. 小程序的功能是对Excel进行一些分析.验证,然 ...

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

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

  7. VSTO学习笔记(一)VSTO概述

    原文:VSTO学习笔记(一)VSTO概述 接触VSTO纯属偶然,前段时间因为忙于一个项目,在客户端Excel中制作一个插件,从远程服务器端(SharePoint Excel Services)上下载E ...

  8. delphi操作xml学习笔记 之一 入门必读

    Delphi 对XML的支持---TXMLDocument类       Delphi7 支持对XML文档的操作,可以通过TXMLDocument类来实现对XML文档的读写.可以利用TXMLDocum ...

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

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

随机推荐

  1. JavaScript 解析 Django Python 生成的 datetime 数据 时区问题解决

    JavaScript 解析 Django/Python 生成的 datetime 数据 当Web后台使用Django时,后台生成的时间数据类型就是Python类型的. 项目需要将几个时间存储到数据库中 ...

  2. THINKPHP源码学习--------文件上传类

    TP图片上传类的理解 在做自己项目上传图片的时候一直都有用到TP的上传图片类,所以要进入源码探索一下. 文件目录:./THinkPHP/Library/Think/Upload.class.php n ...

  3. Opserver简单部署

    版权声明:本文为博主原创文章,未经博主允许不得转载. 一.下载opserver项目 地址:https://github.com/opserver/Opserver/ 二.用vs2012及以上版本打卡o ...

  4. Java GC系列

    一个国外站点的Java JVM调优系列 下面是国内站点翻译的 http://www.importnew.com/1993.html

  5. 【codevs1106】 篝火晚会

    http://codevs.cn/problem/1106/ (题目链接) 题意 将1~n顺序排列的环改成另一个环,问n-不动点数. Solution 啊智障啦,不会做×_× 左转hzwer 代码 / ...

  6. python读取excel一例-------从工资表逐行提取信息

    在工作中经常要用到python操作excel,比如笔者公司中一个人事MM在发工资单的时候,需要从几百行的excel表中逐条的粘出信息,然后逐个的发送到员工的邮箱中.人事MM对此事不胜其烦,终于在某天请 ...

  7. 使用C#把发表的时间改为几年前,几个月,几天前,几小时前,几分钟前,或几秒前

    我们在评论中往往会看到多少天前,多少小时前. 实现原理:现在时间-过去时间 得到的时间差来做比较 下面我定义了一个Helper类,大家直接引用即可,参数就是时间差,注意时间差类型是TimeSpan类型 ...

  8. python命名空间

    在"python之禅"那几句话中有一句:namespace is a good thing. python对于命名空间的处理非常简单,下面的内容不一定真实,完全是我根据现象推测出来 ...

  9. 微信小程序-关于重定向问题

    关于微信的重定向问题 wx.redirectTo(OBJECT) 参数 参数 类型 必填 说明 url 串 是 需要跳转的应用内页面的路径 成功 功能 否 接口调用成功的回调函数 失败 功能 否 接口 ...

  10. mysql 基本操作

    创建数据库 create database studentdb charset utf8; #创建数据库 create database studentdb charset utf8; #查看数据库的 ...