2013-07-25 25 views
5

我正在創建一個讀取製表符分隔文本文件的小應用程序,進行一些更改,然後創建一個Excel 2007 .xlsx文件。我在計算如何從字符串數組中取出行並將它們寫入Excel文件時遇到了困難,使用選項卡將行分成列。我希望這是有道理的。如何使用製表符分隔符將字符串數組寫入Excel文件?

我有string Lines[]包含這樣的事情:

Item1\tItem2\tItem3\tItem4 
ItemA\tItemB\tItemC\tItemD 
Item5\tItem6\tItem7\tItem8 

我想創建一個看起來像這樣的Excel文件:

A  B  C  D 
Item1 Item2 Item3 Item4 
ItemA ItemB ItemC ItemD 
Item5 Item6 Item7 Item8 

我嘗試以下,但它只是放第一行從Lines[]分成每一行,並且不分隔成列:

string Lines[] = GetLines(); 

Excel.Application xlApp; 
Excel.Workbook xlWb; 
Excel.Worksheet xlWs; 
object misValue = System.Reflection.Missing.Value; 

xlApp = new Excel.Application(); 
xlWb = xlApp.Workbooks.Add(misValue); 
xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1); 

Excel.Range c1 = (Excel.Range)xlWs.Cells[2, 1]; 
Excel.Range c2 = (Excel.Range)xlWs.Cells[2 + lines.Length, 1]; 

Excel.Range range = xlWs.get_Range(c1, c2); 

range.Value = lines; 
range.TextToColumns(     
    range, 
    Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited, 
    Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone, 
    false, 
    true // This is flag to say it is tab delimited 
); 

xlApp.Visible = true; 

任何意見將不勝感激!謝謝!

這裏是目前我得到的輸出:

A       B C D 
Item1\tItem2\tItem3\tItem4 
Item1\tItem2\tItem3\tItem4 
Item1\tItem2\tItem3\tItem4 

編輯:我已經更新了我的代碼以@ jiverson的建議,現在該行分成列在Excel,而是從Lines[]第一線仍然出現在Excel的每一行中。爲什麼?

編輯#2:下面是更新工作代碼:

Excel.Application xlApp; 
Excel.Workbook xlWb; 
Excel.Worksheet xlWs; 
object misValue = System.Reflection.Missing.Value; 

xlApp = new Excel.Application(); 
xlWb = xlApp.Workbooks.Add(misValue); 
xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1); 

int currentRow = 2; 

string[] lines = GetLines(); 

for (int i = 0; i < lines.Length; i++) 
{ 
    string line = lines[i]; //get the current line 

    string[] values = line.Split('\t'); //split the line at the tabs 

    // 
    // .. i do some things to specific values here .. 
    // 

    lines[i] = String.Join("\t", values); //put the updated line back together 

    Excel.Range currentRange = (Excel.Range)xlWs.Cells[currentRow, 1]; //get the next row 

    currentRange.Value = lines[i]; //write the line to Excel 

    currentRow++; 
} 

Excel.Range c1 = (Excel.Range)xlWs.Cells[2, 1]; //get the first cell 
Excel.Range c2 = (Excel.Range)xlWs.Cells[2 + lines.Length, 1]; //get the last cell 

Excel.Range range = xlWs.get_Range(c1, c2); //set the range as the used area 

range.TextToColumns(//split the row into columns 
    range, 
    Excel.XlTextParsingType.xlDelimited, 
    Excel.XlTextQualifier.xlTextQualifierNone, 
    false, 
    true // This is flag to say it is tab delimited 
); 
+1

使用''\ t''分割字符串並將每個值寫入每個對應的單元格 – chancea

回答

2

循環通過添加每一行,然後使用文本列在設定的範圍值後:

for (int i = 0; i < range.Rows.Count; i++) { 
     range.Rows[i].Value = lines[i]; 
     range.Rows[i].TextToColumns(
      range.Rows[i], 
      Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited, 
      Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone, 
      false, 
      true 
     );   
    } 

MSDN Reference

+0

我試着用製表符分隔,但它不識別'\ t'。這可以首先用'CHR(9)'(Excel)來代替,但在我的例子中我只是使用'〜'。 –

+0

很好啊..那確實把這條線分成了幾列!然而,我仍然只是從每行的'Lines []'獲得第一行。我不確定我做錯了什麼,但我會更新我原來的問題。謝謝! –

+1

我甚至沒有注意到這一點。我會看看是否可以讓其他行工作,而不是重複第一行。 – jiverson

1

這可能會幫助你。 我創建excel文件的方式是從文件中讀取字符串並將消息與數據分開,並使用,分隔,並保存爲.csv文件。

可能是你的情況嘗試用,替換\t,然後嘗試創建該文件。

此代碼可能會給你一個想法。我還沒有測試過它。

1    string filePath = @"C:\test.csv"; 
2    string delimiter = ","; 
3  
4    string[][] output = new string[][]{ 
5     new string[]{"Col 1 Row 1", "Col 2 Row 1", "Col 3 Row 1"}, 
6     new string[]{"Col1 Row 2", "Col2 Row 2", "Col3 Row 2"} 
7    }; 
8    int length = output.GetLength(0); 
9    StringBuilder sb = new StringBuilder(); 
10    for (int index = 0; index < length; index++) 
11     sb.AppendLine(string.Join(delimiter, output[index])); 
12 
13    File.WriteAllText(filePath, sb.ToString()); 
+0

我剛剛給出了一個嘗試,它只是放一個','而不是'\ t' ..仍然沒有將字符串分成多列。 –

+0

然後可以嘗試@chancea說 –

+0

我以前將字符串數組保存到一個.txt文件,然後手動將該文件導入Excel,這很好用..我只是想避免手動步驟並以編程方式創建Excel文件。 –

1

您可以使用標籤'\t'分裂在lines[]每個字符串,然後只寫每個值輸出到相應的單元格。這是應該讓你開始這一個例子:

for(int i = 0; i < lines.Length; i++) 
    { 
     String line = lines[i]; 

     Excel.Range c1 = (Excel.Range)xlWs.Cells[i+1, 1]; 
     Excel.Range c2 = (Excel.Range)xlWs.Cells[i+1, 1 + line.Length]; 
     Excel.Range range = xlWs.get_Range(c1, c2); 
     string[] split = line.Split('\t'); 
     for (int c = 1; c <= split.Length; c++) 
     { 
      range.Cells[1, c] = split[c-1]; 
     } 
    } 
+0

謝謝..這看起來像它會工作。但是,我選擇逐行寫入而不是逐個寫入。不過謝謝你向我展示如何以這種方式做到這一點! –

1

你可能對使用Excel的Text to Columns功能感興趣,該功能對於大型數據集更有效,而不是循環遍歷單元格。

以下是您可能適用於從C#運行的Excel錄製的宏。我首先將\t轉換爲~,但它可能是其他一些字符。

Sub Macro1() 
    Selection.Replace What:="\t", Replacement:="~", LookAt:=xlPart, _ 
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
     ReplaceFormat:=False 
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _ 
     TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _ 
     Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ 
     :="~", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), _ 
     TrailingMinusNumbers:=True 
End Sub 

修改從C#工作可能有點棘手,但它有助於瞭解此選項。

+0

謝謝..「Text to Columns」確實將行分割成列,但我仍然只從每行出現的Lines []出現第一行。 –

相關問題