Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

excel

I'm creating a small app that reads a tab delimited text file, makes a few changes, and then creates an Excel 2007 .xlsx file. I'm having trouble figuring out how to take the lines from a string array and write them to the Excel file, using the tabs to break the line up into columns. I hope that made sense.

I have string Lines[] that contains something like this:

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

I'd like to create an Excel file that looks like this:

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

I tried the following, but it just puts the first line from Lines[] into each row, and doesn't separate into columns:

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;

Any advice would be appreciated! Thank you!

Here's the output I'm currently getting:

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

EDIT: I've updated my code with @jiverson's suggestion and the line is now separated into columns in Excel, but the first line from Lines[] still appears in every row in Excel. Why?

EDIT #2: Here's the updated working code:

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
);
like image 299
Jeff Brady Avatar asked Jul 25 '13 16:07

Jeff Brady


2 Answers

Loop through to add each line and then use text to columns after you set the range value:

    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

like image 51
jiverson Avatar answered Oct 11 '22 13:10

jiverson


This may help you. The way I created excel file is to read the string from the file and message the data and separated with , and save as .csv file.

May be in your case try to replace the \t with the , and then try to create the file.

This code may give you an idea. I haven't tested it though.

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());
like image 22
gmail user Avatar answered Oct 11 '22 13:10

gmail user