Using DocumentFormat.OpenXml to generate a new excel file in terms of temp excel file

  1 public class PortfolioReport    
  2     {
  3         string TemplateFileName = "Temp.xlsx";
  4         string NewFileName = @"C:\NewFile.xlsx";
  5 
  6         private WorkbookPart WbPart = null;
  7 
  8         //Manager function
  9         public PortfolioReport()
 10         {
 11             CopyFile(TemplateFileName, NewFileName);
 12             SpreadsheetDocument document = SpreadsheetDocument.Open(NewFileName, true);
 13 
 14             WbPart = document.WorkbookPart;
 15             UpdateValue("Summarizing Report", "A4", "A4.Value", 0, true);
 16             UpdateValue("Synchronization Report", "D4", "D4.Value", 0, true);
 17             RemoveCellValue("Synchronization Report", "E1");
 18             document.Close();
 19         }
 20 
 21         //Remove the cell value
 22         private bool RemoveCellValue(string sheetName, string addressName)
 23         {
 24             bool returnValue = false;
 25 
 26             Sheet sheet = WbPart.Workbook.Descendants<Sheet>().
 27                 Where(s => s.Name == sheetName).FirstOrDefault();
 28             if (sheet != null)
 29             {
 30                 Worksheet ws = ((WorksheetPart)(WbPart.GetPartById(sheet.Id))).Worksheet;
 31                 Cell cell = InsertCellInWorksheet(ws, addressName);
 32 
 33                 // If there is a cell value, remove it to force a recalculation
 34                 // on this cell.
 35                 if (cell.CellValue != null)
 36                 {
 37                     cell.CellValue.Remove();
 38                 }
 39 
 40                 // Save the worksheet.
 41                 //ws.Save();
 42                 returnValue = true;
 43             }
 44 
 45             return returnValue;
 46         }
 47 
 48         //Just copy file
 49         private string CopyFile(string source, string dest)
 50         {
 51             string result = "Copied file";
 52             try
 53             {
 54                 // Overwrites existing files
 55                 File.Copy(source, dest, true);
 56             }
 57             catch (Exception ex)
 58             {
 59                 result = ex.Message;
 60             }
 61             return result;
 62         }
 63 
 64         //Update the cell value
 65         public bool UpdateValue(string sheetName, string addressName, string value,
 66                                 UInt32Value styleIndex, bool isString)
 67         {
 68             // Assume failure.
 69             bool updated = false;
 70 
 71             Sheet sheet = WbPart.Workbook.Descendants<Sheet>().Where(
 72                 (s) => s.Name == sheetName).FirstOrDefault();
 73 
 74             if (sheet != null)
 75             {
 76                 Worksheet ws = ((WorksheetPart)(WbPart.GetPartById(sheet.Id))).Worksheet;
 77                 Cell cell = InsertCellInWorksheet(ws, addressName);
 78 
 79                 if (isString)
 80                 {
 81                     // Either retrieve the index of an existing string,
 82                     // or insert the string into the shared string table
 83                     // and get the index of the new item.
 84                     int stringIndex = InsertSharedStringItem(WbPart, value);
 85 
 86                     cell.CellValue = new CellValue(stringIndex.ToString());
 87                     cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
 88                 }
 89                 else
 90                 {
 91                     cell.CellValue = new CellValue(value);
 92                     cell.DataType = new EnumValue<CellValues>(CellValues.Number);
 93                 }
 94 
 95                 if (styleIndex > 0)
 96                     cell.StyleIndex = styleIndex;
 97 
 98                 // Save the worksheet.
 99                 ws.Save();
100                 updated = true;
101             }
102 
103             return updated;
104         }
105 
106         // Given the main workbook part, and a text value, insert the text into 
107         // the shared string table. Create the table if necessary. If the value 
108         // already exists, return its index. If it doesn't exist, insert it and 
109         // return its new index.
110         private int InsertSharedStringItem(WorkbookPart wbPart, string value)
111         {
112             int index = 0;
113             bool found = false;
114             var stringTablePart = wbPart
115                 .GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
116 
117             // If the shared string table is missing, something's wrong.
118             // Just return the index that you found in the cell.
119             // Otherwise, look up the correct text in the table.
120             if (stringTablePart == null)
121             {
122                 // Create it.
123                 stringTablePart = wbPart.AddNewPart<SharedStringTablePart>();
124             }
125 
126             var stringTable = stringTablePart.SharedStringTable;
127             if (stringTable == null)
128             {
129                 stringTable = new SharedStringTable();
130             }
131 
132             // Iterate through all the items in the SharedStringTable. 
133             // If the text already exists, return its index.
134             foreach (SharedStringItem item in stringTable.Elements<SharedStringItem>())
135             {
136                 if (item.InnerText == value)
137                 {
138                     found = true;
139                     break;
140                 }
141                 index += 1;
142             }
143 
144             if (!found)
145             {
146                 stringTable.AppendChild(new SharedStringItem(new Text(value)));
147                 stringTable.Save();
148             }
149 
150             return index;
151         }
152 
153         private Cell InsertCellInWorksheet(Worksheet ws, string addressName)
154         {
155             SheetData sheetData = ws.GetFirstChild<SheetData>();
156             Cell cell = null;
157 
158             UInt32 rowNumber = GetRowIndex(addressName);
159             Row row = GetRow(sheetData, rowNumber);
160 
161             // If the cell you need already exists, return it.
162             // If there is not a cell with the specified column name, insert one.  
163             Cell refCell = row.Elements<Cell>().
164                 Where(c => c.CellReference.Value == addressName).FirstOrDefault();
165             if (refCell != null)
166             {
167                 cell = refCell;
168             }
169             else
170             {
171                 cell = CreateCell(row, addressName);
172             }
173             return cell;
174         }
175 
176         // Add a cell with the specified address to a row.
177         private Cell CreateCell(Row row, String address)
178         {
179             Cell cellResult;
180             Cell refCell = null;
181 
182             // Cells must be in sequential order according to CellReference. 
183             // Determine where to insert the new cell.
184             foreach (Cell cell in row.Elements<Cell>())
185             {
186                 if (string.Compare(cell.CellReference.Value, address, true) > 0)
187                 {
188                     refCell = cell;
189                     break;
190                 }
191             }
192 
193             cellResult = new Cell();
194             cellResult.CellReference = address;
195 
196             row.InsertBefore(cellResult, refCell);
197             return cellResult;
198         }
199 
200         // Return the row at the specified rowIndex located within
201         // the sheet data passed in via wsData. If the row does not
202         // exist, create it.
203         private Row GetRow(SheetData wsData, UInt32 rowIndex)
204         {
205             var row = wsData.Elements<Row>().
206             Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
207             if (row == null)
208             {
209                 row = new Row();
210                 row.RowIndex = rowIndex;
211                 wsData.Append(row);
212             }
213             return row;
214         }
215 
216         // Given an Excel address such as E5 or AB128, GetRowIndex
217         // parses the address and returns the row index.
218         private UInt32 GetRowIndex(string address)
219         {
220             string rowPart;
221             UInt32 l;
222             UInt32 result = 0;
223 
224             for (int i = 0; i < address.Length; i++)
225             {
226                 if (UInt32.TryParse(address.Substring(i, 1), out l))
227                 {
228                     rowPart = address.Substring(i, address.Length - i);
229                     if (UInt32.TryParse(rowPart, out l))
230                     {
231                         result = l;
232                         break;
233                     }
234                 }
235             }
236             return result;
237         }
238     }

 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

posted @ 2013-01-23 18:22  Vincent.Dr  阅读(820)  评论(0编辑  收藏  举报