2

I want to insert an Array of characters into one column of Excel. I normally use something like this to just add a normal string:

lCommand.CommandText += "\"" + row["source"].ToString().Replace("\"", "\"\"").Replace(" ", " ") + "\",";

How would I add an Array of strings to a Column of Excel? Thanks!

0

2 Answers 2

1

See this article:

Fun with Excel--setting a range of cells via an array

I recommend that you read the (short) article, but as a spoiler:

Excel.Range r = this.Range["B2", "B4"];

object[,] workingValues = new object[3, 1];

for (int i = 0; i < 3; i++)
{
    workingValues[i, 0] = i + 2;  // 2,3,4
}

r.Value2 = workingValues;
Sign up to request clarification or add additional context in comments.

Comments

0

You can open the File with C# and write to the cell you want.

First :

using Microsoft.Office.Interop.Excel;

This require you to have COM reference for Excel.

After this you need to open the file you want and set the value. After, you can close the file.

Here is an example. You can always loop for each rows or column for your array.

    _Application docExcel = new Microsoft.Office.Interop.Excel.Application();
    docExcel.Visible = false;
    docExcel.DisplayAlerts = false;

    _Workbook workbooksExcel = docExcel.Workbooks.Open(@"C:\test.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    _Worksheet worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;

    ((Range)worksheetExcel.Cells["1", "A"]).Value2 = "aa";
    ((Range)worksheetExcel.Cells["1", "B"]).Value2 = "bb";

    workbooksExcel.Save();
    workbooksExcel.Close(false, Type.Missing, Type.Missing);
    docExcel.Application.DisplayAlerts = true;
    docExcel.Application.Quit();

Edit:

You can use the Dynamic keyword if you do not want all those Type.Missing parameter :

    _Application docExcel = new Application{Visible = false};

    dynamic workbooksExcel = docExcel.Workbooks.Open(@"C:\test.xlsx");
    var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;

    ((Range)worksheetExcel.Cells["1", "A"]).Value2 = "test1";
    ((Range)worksheetExcel.Cells["1", "B"]).Value2 = "test2";

    workbooksExcel.Save();
    workbooksExcel.Close(false);
    docExcel.Application.Quit();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.