示例#1
0
        public byte[] Export()
        {
            var bytes = File.ReadAllBytes(tempPath);

            using (var ms = new MemoryStream())
            {
                ms.Write(bytes, 0, bytes.Length);
                using (var doc = WordprocessingDocument.Open(ms, true))
                {
                    // 书签名称
                    mainDocumentPart = doc.MainDocumentPart;
                    var body         = doc.MainDocumentPart.Document.Body;
                    var settingsPart = mainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();

                    // Create object to update fields on open
                    var updateFields = new UpdateFieldsOnOpen();
                    updateFields.Val = new OnOffValue(true);

                    // Insert object into settings part.
                    settingsPart.Settings.PrependChild(updateFields);
                    settingsPart.Settings.Save();

                    IDictionary <string, object> main = null;
                    WordTag currentTag = null;
                    if (ds.ContainsKey("main"))
                    {
                        main = ds["main"].First();
                    }

                    // 遍历根级段落
                    var current = body.FirstChild;
                    do
                    {
                        var bStart = HasBookMark(current);
                        if (currentTag == null && bStart != null)
                        {
                            // 是书签的话,加入列表
                            currentTag = new WordTag {
                                Bookmark = bStart
                            };
                        }
                        else if (current is BookmarkEnd bEnd && currentTag != null &&
                                 bEnd.Id == currentTag.Bookmark.Id)
                        {
                            // 此处扩展
                            var bookmark  = currentTag.Bookmark.Name;
                            var dataset   = ds[props.GetValue($"{bookmark}:dataset")];
                            var parentKey = props.GetNullValue($"{bookmark}:parent");
                            if (parentKey != null)
                            {
                                // 定义了父链字段
                                var parentVal = "";
                                if (parentKey.HasValue())
                                {
                                    parentVal = main.GetValue(parentKey, "");
                                }
                                dataset = dataset.Where(r =>
                                {
                                    var row = r as IDictionary <string, object>;
                                    return(row.GetValue("parentid", "") == parentVal);
                                });
                            }
                            ExpandBookmark(body, currentTag, bEnd, dataset);

                            // 设为非书签状态
                            bStart     = null;
                            currentTag = null;
                        }
                        else if (currentTag != null)
                        {
                            currentTag.Add(current);

                            var previous = current.PreviousSibling();
                            current.Remove();
                            current = previous;
                        }
                        else if (current is Table table)
                        {
                            ExpandTable(table, main);
                        }
                        else
                        {
                            ReplaceParagraph(current, main);
                        }

                        // 取下一对象
                        current = current.NextSibling();
                    }while (current != null);
                }

                return(ms.ToArray());
            }
示例#2
0
        public override void Write()
        {
            ExportFileName = PopulatedName(ExportFileName);
            if (!String.IsNullOrWhiteSpace(ExportFileName))
            {
                DocProperties["FileName"]   = ExportFileName;
                DocProperties["TableCount"] = _dataSet.Tables.Count.ToString();
                if (PopulatePropertiesOnly)
                {
                    if (_dataSet != null)
                    {
                        foreach (DataTable dTable in _dataSet.Tables)
                        {
                            if (dTable.Rows.Count > 0)
                            {
                                foreach (DataColumn dColumn in dTable.Columns)
                                {
                                    DocProperties[dColumn.ColumnName] = dTable.Rows[0][dColumn].ToString();
                                }
                            }
                        }
                    }
                }
                switch (DestinationType)
                {
                case OfficeFileType.WordDocument:
                    WordprocessingDocument doc;
                    if (File.Exists(TemplateFileName))
                    {
                        doc = WordprocessingDocument.CreateFromTemplate(TemplateFileName);
                        doc = (WordprocessingDocument)doc.SaveAs(ExportFileName);
                    }
                    else
                    {
                        doc = WordprocessingDocument.Create(ExportFileName, WordprocessingDocumentType.Document);
                    }
                    CustomFilePropertiesPart customProp = doc.CustomFilePropertiesPart;
                    if (customProp == null)
                    {
                        customProp = doc.AddCustomFilePropertiesPart();
                    }
                    SetFileProperties(customProp);

                    MainDocumentPart mainDoc = doc.MainDocumentPart;
                    if (mainDoc == null)
                    {
                        mainDoc = doc.AddMainDocumentPart();
                    }

                    DocumentSettingsPart settingsPart = mainDoc.GetPartsOfType <DocumentSettingsPart>().First();
                    UpdateFieldsOnOpen   updateFields = new UpdateFieldsOnOpen
                    {
                        Val = new OnOffValue(true)
                    };
                    settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
                    settingsPart.Settings.Save();

                    if (!PopulatePropertiesOnly)
                    {
                        if (mainDoc.Document == null)
                        {
                            mainDoc.Document = new word.Document();
                        }
                        word.Body body       = new word.Body();
                        bool      firstTable = true;
                        foreach (DataTable dt in _dataSet.Tables)
                        {
                            if (!firstTable)
                            {
                                body.Append(GetPageBreak());
                            }
                            else
                            {
                                firstTable = false;
                            }
                            body.Append(GetParagraph(dt.TableName));
                            body.Append(GetWordTable(dt));
                        }
                        mainDoc.Document.Append(body);
                    }
                    mainDoc.Document.Save();
                    doc.Dispose();
                    break;

                case OfficeFileType.ExcelWorkbook:
                    SpreadsheetDocument spreadSheet;
                    if (File.Exists(TemplateFileName))
                    {
                        spreadSheet = SpreadsheetDocument.CreateFromTemplate(TemplateFileName);
                        spreadSheet = (SpreadsheetDocument)spreadSheet.SaveAs(ExportFileName);
                    }
                    else
                    {
                        spreadSheet = SpreadsheetDocument.Create(ExportFileName, SpreadsheetDocumentType.Workbook);
                        spreadSheet.Save();
                    }
                    using (SpreadsheetDocument workbook = spreadSheet)
                    {
                        CustomFilePropertiesPart excelCustomProp = workbook.AddCustomFilePropertiesPart();
                        SetFileProperties(excelCustomProp);

                        if (workbook.WorkbookPart == null)
                        {
                            workbook.AddWorkbookPart();
                        }
                        if (workbook.WorkbookPart.Workbook == null)
                        {
                            workbook.WorkbookPart.Workbook = new excel.Workbook();
                        }
                        if (workbook.WorkbookPart.Workbook.Sheets == null)
                        {
                            workbook.WorkbookPart.Workbook.Sheets = new excel.Sheets();
                        }
                        excel.Sheets sheets = workbook.WorkbookPart.Workbook.Sheets;
                        foreach (DataTable table in _dataSet.Tables)
                        {
                            excel.SheetData sheetData = null;
                            WorksheetPart   sheetPart = null;
                            excel.Sheet     sheet     = null;
                            foreach (OpenXmlElement element in sheets.Elements())
                            {
                                if (element is Sheet)
                                {
                                    sheet = (Sheet)element;
                                    if (sheet.Name.Value.Equals(table.TableName, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        //Assign the sheetPart
                                        sheetPart = (WorksheetPart)workbook.WorkbookPart.GetPartById(sheet.Id.Value);
                                        sheetData = sheetPart.Worksheet.GetFirstChild <SheetData>();
                                        break;
                                    }
                                }
                                sheet = null;
                            }

                            if (sheet == null)
                            {
                                sheetPart           = workbook.WorkbookPart.AddNewPart <WorksheetPart>(); //Create a new WorksheetPart
                                sheetData           = new excel.SheetData();                              //create a new SheetData
                                sheetPart.Worksheet = new excel.Worksheet(sheetData);                     /// Create a new Worksheet with the sheetData and link it to the sheetPart...

                                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);     //get the ID of the sheetPart.
                                sheet = new excel.Sheet()
                                {
                                    Id = relationshipId, SheetId = 1, Name = table.TableName
                                };                        //create a new sheet
                                sheets.Append(sheet);     //append the sheet to the sheets.
                            }

                            List <String> columns = new List <string>();
                            foreach (System.Data.DataColumn column in table.Columns)
                            {
                                columns.Add(column.ColumnName);
                            }
                            if (PrintTableHeader)
                            {
                                excel.Row headerRow = new excel.Row();

                                foreach (string column in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(GetColumnName(table.Columns[column]))
                                    };
                                    headerRow.AppendChild(cell);
                                }


                                sheetData.AppendChild(headerRow);
                            }

                            foreach (DataRow dsrow in table.Rows)
                            {
                                excel.Row newRow = new excel.Row();
                                foreach (String col in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(dsrow[col].ToString())     //
                                    };
                                    newRow.AppendChild(cell);
                                }

                                sheetData.AppendChild(newRow);
                            }
                            sheetPart.Worksheet.Save();
                        }
                        workbook.WorkbookPart.Workbook.Save();
                        workbook.Save();
                        workbook.Close();
                    }

                    break;
                }
            }
        }
        /// <summary>
        /// Gets the custom XML from the main document part.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <returns>The custom XML as a <see cref="XElement" />.</returns>
        public static XElement GetCustomXml(this MainDocumentPart mainPart)
        {
            CustomXmlPart customXmlPart = mainPart.GetPartsOfType <CustomXmlPart>().FirstOrDefault();

            return(customXmlPart == null ? null : customXmlPart.GetXDocument().Root);
        }