2013-05-17 67 views
6

我在嘗試將數據從DataTable寫入數據表 - 不幸的是,這並不像預期的那樣工作, G。 DataSheet已損壞。Office Open XMl SDK將數字寫入工作表

我使用下面的代碼:

private void AddDataToSheet(ExcelViewData data, SheetData sheetData) 
      { 
       var excelData = data.WriteableDataTable; 
//// this returns a datatable 
////the numbers have a format like "8,1" "8,0" etc. 
       for (int i = 0; i < excelData.Rows.Count; i++) 
       { 
        Row row = new Row(); 
        //row.RowIndex = (UInt32)i; 
        for (int c = 0; c < excelData.Columns.Count; c++) 
        { 
         Cell cell = new Cell(); 
         CellValue cellvalue = new CellValue(); 
         //cell.CellReference = SharedMethods.GetExcelColumnName(i + 1) + (c + 1).ToString(); 
         cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number; 
         cellvalue.Text = excelData.Rows[i][c].ToString().Replace(",","."); 
         cell.Append(cellvalue); 
         row.Append(cell); 
        } 

        sheetData.Append(row); 
       } 
      } 

任何想法,爲什麼失敗?我似乎有多個教程使用相同的方法。

回答

4

試試這個方法:

public void InsertDataTableIntoExcel(SpreadsheetDocument _excelDoc, SheetData SheetData, DataTable excelData, int rowIndex = 1) 
    { 
     if (_excelDoc != null && SheetData != null) 
     { 
      if (excelData.Rows.Count > 0) 
      { 
       try 
       { 
        uint lastRowIndex = (uint)rowIndex; 
        for (int row = 0; row < excelData.Rows.Count; row++) 
        { 
         Row dataRow = GetRow(lastRowIndex, true); 
         for (int col = 0; col < excelData.Columns.Count; col++) 
         { 
          Cell cell = GetCell(dataRow, col + 1, lastRowIndex); 

          string objDataType = excelData.Rows[row][col].GetType().ToString(); 
          //Add text to text cell 
          if (objDataType.Contains(TypeCode.Int32.ToString()) || objDataType.Contains(TypeCode.Int64.ToString()) || objDataType.Contains(TypeCode.Decimal.ToString())) 
          { 
           cell.DataType = new EnumValue<CellValues>(CellValues.Number); 
           cell.CellValue = new CellValue(objData.ToString()); 
          } 
          else 
          { 
           cell.CellValue = new CellValue(objData.ToString()); 
           cell.DataType = new EnumValue<CellValues>(CellValues.String); 
          } 
         } 
         lastRowIndex++; 
        } 
       } 
       catch (OpenXmlPackageException ex) 
       { 
        throw ex; 
       } 
       catch (Exception ex) 
       { 
        throw ex; 
       } 
      } 
      else 
      { 
       OpenXmlPackageException openEx = new OpenXmlPackageException("No data from datatable"); 
       throw openEx; 
      } 
     } 
     else 
     { 
      OpenXmlPackageException openEx = new OpenXmlPackageException("Workbook not found"); 
      throw openEx; 
     } 
    } 
+0

謝謝你的代碼 - unfortuanetly,我開始在一個完美的白紙,沒有行寫。 我會嘗試一下內部代碼 - 它看起來非常有前途! –

+0

它是一種運行良好的新方法,您可以使用創建單元格的代碼並添加單元格值和單元格類型,這只不過是單元格的格式。我希望這給你的答案。 – KirtiSagar

+0

它的工作,謝謝! :) –