trytocode
trytocode

Reputation: 403

How to insert a result of split word into cells in Excel with C#

I've got a task to split a line from text file, then put each word from the split result into Excel cells.

I think I've done it right, but it always gives me an exception.

var lines = File.ReadAllLines(textBox1.Text);
//baca line lalu split 
xlApp = new excel.Application();
xlWb = xlApp.Workbooks.Add();
xlWs = (excel.Worksheet)xlWb.Worksheets.get_Item(1);
string appPath = AppDomain.CurrentDomain.BaseDirectory;
for (int i = 0; i < lines.Length; i++)
{
    textsplit = lines[i].Split('@');
    for (int j = 0; j < textsplit.Length; j++)
    {
        //masukin ke cells
        xlWs.Cells[row, j + 1] = textsplit[j].ToString();
    }
    row++;
}
xlWb.SaveAs(appPath + "testing.xlsx", excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,
    false, false, excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
xlWb.Close();
closeExcel(xlApp); closeExcel(xlApp);

The Exception:

System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)

I don't know what I did wrong. When I try to insert the cell with hardcode like xlWs.Cells[1,1] = "a", it works perfectly fine.

Upvotes: 1

Views: 122

Answers (1)

Branden
Branden

Reputation: 347

xlWs.Cells[row, j + 1] = textsplit[j].ToString();

I believe you are getting this error because row may have the incorrect value assigned. It may be null?

Try replacing row with your variable "i" from your first loop and it should work fine as I expect you have intended.

Upvotes: 0

Related Questions