2014-03-06 77 views
0

我正在處理一個應用程序,該應用程序必須將每行的所有貴重物品轉換爲rtf文檔。我使用的excel文件有超過10.000行但只有5列。 到目前爲止,我可以使用Value2.ToString方法讀取文件。 我想要做的是從各行獲得5個價值觀,爲他們提供一個頭c#excel格式rtf中的每一行

使用firstText = CEL A1

secondtext = CEL B1的文本

thirdtext文= CEL c1的文本

fourthtext = CEL d1的文本

fifttext = CEL e1的文本

並做CEL A2,B2等等等等 我的代碼相同到目前爲止

  //Create COM Objects. 
     Excel.Application xlApp = new Excel.Application(); 
     Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\aaa.xlsx"); 
     Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; 
     Excel.Range xlRange = xlWorksheet.UsedRange; 
     int rowCount = xlRange.Rows.Count; 
     int colCount = xlRange.Columns.Count; 

     //iterate over the rows and columns and print to the console as it appears in the file 
     //excel is not zero based!! 
     for (int i = 1; i <= rowCount; i++) 
     { 
      for (int j = 1; j <= colCount; j++) 
      { 
       //new line 
       if (j == 1) 
        Console.WriteLine("\r\n"); 

       //write the value to the console 
       if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) 
        Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t", "\r\n"); 

      } 

      // Console.ReadLine(); for testing purposes   
     } 

     //cleanup 

     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 

     // rule of thumb for releasing com objects: 
     // never use two dots, all COM objects must be referenced and released individually 
     // ex: [somthing].[something].[something] is bad 

     //release com objects to fully kill excel process from running in the background 
     Marshal.ReleaseComObject(xlRange); 
     Marshal.ReleaseComObject(xlWorksheet); 

     //close and release 
     xlWorkbook.Close(); 
     Marshal.ReleaseComObject(xlWorkbook); 

     //quit and release 
     xlApp.Quit(); 
     Marshal.ReleaseComObject(xlApp); 
     Console.ReadLine(); 

任何幫助,將不勝感激

+0

什麼是你的問題或問題? – faceman

+0

我的問題是,如何讀取每行的值並將其發送到帶有上述標題的文本文件,然後單元格值爲 – Wigle

回答

1

我還不能肯定你的問題是什麼?

你只是問如何添加標題?

//iterate over the rows and columns and print to the console as it appears in the file 
//excel is not zero based!! 
for (int i = 1; i <= rowCount; i++) 
{ 
    for (int j = 1; j <= colCount; j++) 
    { 
     //new line 
     if (j == 1) 
      Console.WriteLine("\r\n"); 

     //write the value to the console 
     if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) 
      Console.Write("{0}= ", GetHeaderText(j)); 
      Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t", "\r\n"); 
    } 
    // Console.ReadLine(); for testing purposes   
} 

獲得通過一些輔助方法的標題文字:

private string GetHeaderText(int colId) 
{ 
    switch (colId) 
    { 
     case 1: 
      return "firsttext"; 
     case 2: 
      return "secondtext"; 
     case 3: 
      return "thirdtext"; 
     case 4: 
      return "fourthtext"; 
     case 5: 
      return "fithtext"; 
     default: 
      return "header not defined"; 
    } 
} 
+1

這是解決方案,非常感謝! – Wigle