We help IT Professionals succeed at work.

Appending Array to Excel Using C#

ak5745
ak5745 asked
on
Experts,

I'm trying to append an array of strings to an already existing Excel 2007 file - there's already data in the file, and I'd like to add my new data to the first empty row.

As File.AppendAllText doesn't exist in this context, is there something that will give me the same usability? Any tips? Thanks!
Comment
Watch Question

Michael FowlerSolutions Consultant

Commented:
While I am sure there are other methods I would create a csv file with C# and then use a macro in the excel document to import the data from the csv. While this is a two step process it is easy to implement

Michael

Author

Commented:
Thanks for the reply. I'd like to have the capability of opening Excel and having all my data there already without having any additional steps.

If this is not possible, then I'll probably lean towards the csv route.

Any other ideas?
Michael FowlerSolutions Consultant

Commented:
The only thing I can think of is

Save as csv
Create an excel document with a macro that opens the required file and the csv and then appends the data the existing file
Set the macro to run on file open
Call this document from your application

Problem is that this method is messy and there must be a better way to solve the issue

Michael

Author

Commented:
You're right, it is messy. I know what I'm describing here is essentially a log in excel. Given I can do this, I'd like entries to be added with most recent being placed on top (below a header), where I'll eventually use excel to do analysis of this data.

Author

Commented:
Does anyone already do this in any apps they manage? It doesn't strike me as cosmic, but maybe it is. Anyone have any tips/code snippets that might help me out?

Thanks.
Commented:
Here's what I found that works for me. Your mileage may vary:

public static void WriteArray(Dictionary<string, object[]> data, string stock)
        {
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook excelbk = excelApp.Workbooks.Open("C:\\TestSheet.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);
            Excel.Worksheet worksheet = (Excel.Worksheet)excelbk.Worksheets["Sheet1"];

            worksheet.get_Range("A3", "A3").EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, false);

            //Array starting at 3,1 (row 3 column 1).
            var startCell = (Excel.Range)worksheet.Cells[3, 1];

            //Array ending at 3, 18 (row 3 column 18).
            var endCell = (Excel.Range)worksheet.Cells[3, 18];

            var writeRange = worksheet.Range[startCell, endCell];

            //Write array.
            writeRange.Value2 = data[stock];

            excelbk.Save();
            excelbk.Close();
            excelApp.Quit();
            releaseObject(worksheet);
            releaseObject(excelbk);
            releaseObject(excelApp);
        }

        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        } 

Open in new window


Sources:
http://www.clear-lines.com/blog/post/Write-data-to-an-Excel-worksheet-with-C-fast.aspx 
http://csharp.net-informations.com/excel/csharp-open-excel.htm

Hope this helps anyone else who might need it.

If anyone would like to optimize this, please do so before it's closed.

Thanks

Author

Commented:
I found a solution that works for me. Hope it's useful.