C# 如何使用制表符分隔符将字符串数组写入Excel文件?

C# 如何使用制表符分隔符将字符串数组写入Excel文件?,c#,excel,C#,Excel,我正在创建一个小应用程序,它读取一个以制表符分隔的文本文件,进行一些更改,然后创建一个Excel2007.xlsx文件。我不知道如何从字符串数组中提取行并将它们写入Excel文件,使用选项卡将行拆分为列。我希望这是有道理的 我有字符串行[],其中包含如下内容: Item1\tItem2\tItem3\tItem4 ItemA\tItemB\tItemC\tItemD Item5\tItem6\tItem7\tItem8 A B C D Item1 Item2

我正在创建一个小应用程序,它读取一个以制表符分隔的文本文件,进行一些更改,然后创建一个Excel2007.xlsx文件。我不知道如何从字符串数组中提取行并将它们写入Excel文件,使用选项卡将行拆分为列。我希望这是有道理的

我有
字符串行[]
,其中包含如下内容:

Item1\tItem2\tItem3\tItem4
ItemA\tItemB\tItemC\tItemD
Item5\tItem6\tItem7\tItem8
A      B      C      D
Item1  Item2  Item3  Item4
ItemA  ItemB  ItemC  ItemD
Item5  Item6  Item7  Item8
我想创建一个Excel文件,如下所示:

Item1\tItem2\tItem3\tItem4
ItemA\tItemB\tItemC\tItemD
Item5\tItem6\tItem7\tItem8
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
);
Excel.Application xlApp;
Excel.xlWb工作手册;
Excel.xlWs工作表;
对象错误值=System.Reflection.Missing.Value;
xlApp=new Excel.Application();
xlWb=xlApp.Workbooks.Add(misValue);
xlWs=(Excel.Worksheet)xlWb.Worksheets.get_项(1);
int currentRow=2;
字符串[]行=GetLines();
对于(int i=0;i
这可能会对您有所帮助。 我创建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());
1字符串文件路径=@“C:\test.csv”;
2字符串分隔符=“,”;
3.
4字符串[][]输出=新字符串[][]{
5新字符串[]{“列1第1行”、“列2第1行”、“列3第1行”},
6新字符串[]{“Col1第2行”、“Col2第2行”、“Col3第2行”}
7               };  
8 int length=output.GetLength(0);
9 StringBuilder sb=新StringBuilder();
10表示(int-index=0;index
您可以使用选项卡
'\t'
拆分
行[]
中的每个字符串,然后将每个值写入相应的单元格。下面是一个应该让您开始学习的示例:

 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];
       }
   }
for(int i=0;i对于(int c=1;c循环通过以添加每一行,然后在设置范围值后将文本用于列):

    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
        );          
    }
for(int i=0;i

您可能会对使用Excel的
文本到列
功能感兴趣,这对于大型数据集来说更有效,而不是在单元格中循环

下面是一个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));
         }
     }
 }
publicstaticvoidwritetocvs(此T[,]数组,字符串文件名)
{
使用(var stream=File.CreateText(文件名))
{
for(int i=0;i
使用
'\t'
拆分字符串,并将每个值写入每个对应的单元格。我只是尝试了一下,它只放入了
,而不是
\t
。仍然没有将字符串拆分为列。然后可能会尝试,因为@chancea saidI之前将字符串数组保存到.txt文件中,然后手动导入将文件转换为Excel非常有效。我只是想避免手动步骤,以编程方式创建Excel文件。@JeffBrady我可能会这样做;)是的,我可能需要逐行循环遍历数组。我尝试使用制表符分隔,但它无法识别
\t
。这