Using DocumentFormat.OpenXml to generate a new excel file in terms of temp excel file
2013-01-23 18:22
836 查看
public class PortfolioReport { string TemplateFileName = "Temp.xlsx"; string NewFileName = @"C:\NewFile.xlsx"; private WorkbookPart WbPart = null; //Manager function public PortfolioReport() { CopyFile(TemplateFileName, NewFileName); SpreadsheetDocument document = SpreadsheetDocument.Open(NewFileName, true); WbPart = document.WorkbookPart; UpdateValue("Summarizing Report", "A4", "A4.Value", 0, true); UpdateValue("Synchronization Report", "D4", "D4.Value", 0, true); RemoveCellValue("Synchronization Report", "E1"); document.Close(); } //Remove the cell value private bool RemoveCellValue(string sheetName, string addressName) { bool returnValue = false; Sheet sheet = WbPart.Workbook.Descendants<Sheet>(). Where(s => s.Name == sheetName).FirstOrDefault(); if (sheet != null) { Worksheet ws = ((WorksheetPart)(WbPart.GetPartById(sheet.Id))).Worksheet; Cell cell = InsertCellInWorksheet(ws, addressName); // If there is a cell value, remove it to force a recalculation // on this cell. if (cell.CellValue != null) { cell.CellValue.Remove(); } // Save the worksheet. //ws.Save(); returnValue = true; } return returnValue; } //Just copy file private string CopyFile(string source, string dest) { string result = "Copied file"; try { // Overwrites existing files File.Copy(source, dest, true); } catch (Exception ex) { result = ex.Message; } return result; } //Update the cell value public bool UpdateValue(string sheetName, string addressName, string value, UInt32Value styleIndex, bool isString) { // Assume failure. bool updated = false; Sheet sheet = WbPart.Workbook.Descendants<Sheet>().Where( (s) => s.Name == sheetName).FirstOrDefault(); if (sheet != null) { Worksheet ws = ((WorksheetPart)(WbPart.GetPartById(sheet.Id))).Worksheet; Cell cell = InsertCellInWorksheet(ws, addressName); if (isString) { // Either retrieve the index of an existing string, // or insert the string into the shared string table // and get the index of the new item. int stringIndex = InsertSharedStringItem(WbPart, value); cell.CellValue = new CellValue(stringIndex.ToString()); cell.DataType = new EnumValue<CellValues>(CellValues.SharedString); } else { cell.CellValue = new CellValue(value); cell.DataType = new EnumValue<CellValues>(CellValues.Number); } if (styleIndex > 0) cell.StyleIndex = styleIndex; // Save the worksheet. ws.Save(); updated = true; } return updated; } // Given the main workbook part, and a text value, insert the text into // the shared string table. Create the table if necessary. If the value // already exists, return its index. If it doesn't exist, insert it and // return its new index. private int InsertSharedStringItem(WorkbookPart wbPart, string value) { int index = 0; bool found = false; var stringTablePart = wbPart .GetPartsOfType<SharedStringTablePart>().FirstOrDefault(); // If the shared string table is missing, something's wrong. // Just return the index that you found in the cell. // Otherwise, look up the correct text in the table. if (stringTablePart == null) { // Create it. stringTablePart = wbPart.AddNewPart<SharedStringTablePart>(); } var stringTable = stringTablePart.SharedStringTable; if (stringTable == null) { stringTable = new SharedStringTable(); } // Iterate through all the items in the SharedStringTable. // If the text already exists, return its index. foreach (SharedStringItem item in stringTable.Elements<SharedStringItem>()) { if (item.InnerText == value) { found = true; break; } index += 1; } if (!found) { stringTable.AppendChild(new SharedStringItem(new Text(value))); stringTable.Save(); } return index; } private Cell InsertCellInWorksheet(Worksheet ws, string addressName) { SheetData sheetData = ws.GetFirstChild<SheetData>(); Cell cell = null; UInt32 rowNumber = GetRowIndex(addressName); Row row = GetRow(sheetData, rowNumber); // If the cell you need already exists, return it. // If there is not a cell with the specified column name, insert one. Cell refCell = row.Elements<Cell>(). Where(c => c.CellReference.Value == addressName).FirstOrDefault(); if (refCell != null) { cell = refCell; } else { cell = CreateCell(row, addressName); } return cell; } // Add a cell with the specified address to a row. private Cell CreateCell(Row row, String address) { Cell cellResult; Cell refCell = null; // Cells must be in sequential order according to CellReference. // Determine where to insert the new cell. foreach (Cell cell in row.Elements<Cell>()) { if (string.Compare(cell.CellReference.Value, address, true) > 0) { refCell = cell; break; } } cellResult = new Cell(); cellResult.CellReference = address; row.InsertBefore(cellResult, refCell); return cellResult; } // Return the row at the specified rowIndex located within // the sheet data passed in via wsData. If the row does not // exist, create it. private Row GetRow(SheetData wsData, UInt32 rowIndex) { var row = wsData.Elements<Row>(). Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault(); if (row == null) { row = new Row(); row.RowIndex = rowIndex; wsData.Append(row); } return row; } // Given an Excel address such as E5 or AB128, GetRowIndex // parses the address and returns the row index. private UInt32 GetRowIndex(string address) { string rowPart; UInt32 l; UInt32 result = 0; for (int i = 0; i < address.Length; i++) { if (UInt32.TryParse(address.Substring(i, 1), out l)) { rowPart = address.Substring(i, address.Length - i); if (UInt32.TryParse(rowPart, out l)) { result = l; break; } } } return result; } }
Calling example (Console Application):
class Program { static void Main(string[] args) { new PortfolioReport(); } }
More info please click the url as below:
http://msdn.microsoft.com/en-us/library/office/hh180830(v=office.14).aspx
相关文章推荐
- Creation of a Word 2007 document using the Open XML Format SDK
- csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net
- How to avoid Excel from prompting "The file you are trying to open, , is in a different format than specified by the file extension"? (转)
- How To Generate An XML File As A Target Datastore Using ODI In An Integration Interface ? [ID 454268
- Upload Data from Excel File in ABAP using TEXT_CONVERT_XLS_TO_SAP
- Preview Word files (docx) in HTML using ASP.NET, OpenXML and LINQ to XML
- ExcelPackage: Office Open XML Format file creation
- Preview Word files (docx) in HTML using ASP.NET, OpenXML and LINQ to XML
- How can I force Python's file.write() to use the same newline format in Windows as in Linux (“\r\n”
- Creating a new Microsoft Word document from a template using OpenXml
- Linux - How to remove the new line at the end of file when using vim
- [PHP] To display some attribute of the node in the XML document.
- "The file you are trying to open, '[filename]', is in a different format" Excel Error
- [OpenXml] Generate excel in memory and dump to file
- 奇葩问题:This file could not be checked in because the original version of the file on the server was moved or deleted. A new version of this file has been saved to the server, but your check-in comments were not saved
- Csharp: read excel file using Open XML SDK 2.5
- Using Visual Basic and ASP with XML to Generate Excel 2003 Workbooks
- How to convert Word table into Excel using OpenXML
- How-to find the SQL that using lots of temp tablespace in Oracle
- csharp:using OpenXml SDK 2.0 and ClosedXML read excel file