簡體   English   中英

如何使用制表符分隔符將字符串數組寫入Excel文件?

[英]How can I write a string array to Excel file, with a tab delimiter?

我正在創建一個小型應用程序,該應用程序讀取制表符分隔的文本文件,進行一些更改,然后創建一個Excel 2007 .xlsx文件。 我很難弄清楚如何從字符串數組中提取行並將其寫入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
);

循環以添加每一行,然后在設置范圍值后在列中使用文本:

    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參考

這可能對您有幫助。 我創建excel文件的方法是從文件中讀取字符串並向數據發送消息,並用分隔,然后另存為.csv文件。

在您的情況下,請嘗試將\\t替換為\\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());

您可以使用選項卡'\\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];
       }
   }

您可能對使用Excel的“ Text to Columns功能感興趣,該功能對於大型數據集將比在單元格中循環更有效。

以下是一個Excel記錄的宏,您可以使其適合從C#運行。 我首先將\\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#進行修改可能有點棘手,但是了解此選項很有用。

我發現更容易的方法是,將錯誤值簡單地寫入.csv文件,然后在Excel中打開它,從而減少了錯誤。

 public static void WriteToCvs<T>(this T[,] array, string fileName)
 {
     using (var stream = File.CreateText(fileName))
     {
         for (int i = 0; i < array.GetLength(0); i++)
         {
             var values = new List<T>();

             for (int j = 0; j < array.GetLength(1); j++)
             {
                 values.Add(array[i, j]);
             }

             stream.WriteLine(string.Join(",", values));
         }
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM