2012-01-05 99 views
0

我有這樣的DataTable到Excel通過OpenXML的

 

Col1 Col2 Col3  col4 
GRPs 2009 69952.4  a 
GRPs 2010 58949.8  a 
GRPs 2009 37251.2  b 
GRPs 2010 35433.9  b 
GRPs 2009 28039.2  c 
GRPs 2010 35079.4  c 
SOC  2009 69952.4  a 
SOC  2010 58949.8  a 
SOC  2009 37251.2  b 
SOC  2010 35433.9  b 
SOC  2009 28039.2  c 
SOC  2010 35079.4  c 

一個DataTable,我需要一個使用的OpenXML這種格式

 
    A  B   C   D  E  F  G  H  I 
1   2009  2010    2009 2010   2009  2010 
2 GRPs 69952.4 58949.8   37251.2 35433.9   28039.2 35079.4 
3 SOC 69952.4 58949.8   37251.2 35433.9   28039.2 35079.4 

感謝「改造」到一個Excel文件事先

回答

0

它有點像這樣(對不起,這不是完整的代碼,但應該有所幫助):

//Column headers 
static string[] headerColumns = new string[] { "A", "B", "C" }; 

//Used for header column counting 
static string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

     foreach (char c in alphabet.Split(alphabet[dt.Columns.Count])[0]) 
       headerColumns[alphabet.IndexOf(c)] = c.ToString(); 

      //Loops through the data table and appends the data rows onto sheet data 
      for (int r = 0; r < dt.Rows.Count; r++) 
      { 
       //Builds a list of values from the data row 
       List<string> values = new List<string>(); 
       for (int i = 0; i < dt.Columns.Count; i++) 
        values.Add(dt.Rows[r][i].ToString()); 

       //Creates a spreadsheet row from the list of values 
       Spreadsheet.Row contentRow = CreateContentRow(values, r + 2); 

       //Appends the row to the sheetData 
       sheetData.AppendChild(contentRow); 
      } 

    private static Spreadsheet.Row CreateContentRow(List<string> values, int index) 
    { 
     //Create the new row. 
     Spreadsheet.Row r = new Spreadsheet.Row(); 
     r.RowIndex = (UInt32)index; 

     //Create the cells that contain the data. 
     for (int i = 0; i < headerColumns.Length; i++) 
     { 
      Spreadsheet.Cell c = new Spreadsheet.Cell(); 
      c.CellReference = headerColumns[i] + index; 
      Spreadsheet.CellValue v = new Spreadsheet.CellValue(); 
      v.Text = values[i]; 
      c.AppendChild(v); 
      r.AppendChild(c); 
     } 
     return r; 
    } 
+0

親愛的朋友,感謝您的幫助! 我無法發佈圖片,所以我「繪製」EXCEL表格,爲什麼在第二個模式中有大寫字母...... 我並不真的需要它們在代碼中。 – Mac 2012-01-06 12:19:28