Search code examples
c#exceloffice-interop

C# Excel Write to multiple cells


Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.

This is my little method:

public void writeExcelFile()
        {

            string path = @"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
            oXL = new Excel.Application();
            oXL.Visible = true;
            oXL.DisplayAlerts = false;
            mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Get all the sheets in the workbook
            mWorkSheets = mWorkBook.Worksheets;
            //Get the allready exists sheet
            mWSheet1 = (Excel.Worksheet)mWorkSheets.get_Item(1);
            //Excel.Range range = mWSheet1.UsedRange;
            //int colCount = range.Columns.Count;
            //int rowCount = range.Rows.Count;
            int countRows = mWSheet1.UsedRange.Rows.Count;
            int countColumns = mWSheet1.UsedRange.Columns.Count;
            object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;

            for (int index = 1; index < 15; index++)
            {
                mWSheet1.Cells[countRows + index, 1] = countRows + index;
                mWSheet1.Cells[countRows + index, 2] = "test" + index;
            }

            //Excel.Worksheet sheet = workbook.ActiveSheet;
            //Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);

            mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);
            mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
            mWSheet1 = null;
            mWorkBook = null;
            oXL.Quit();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

I tried it with get_range but i get an exception that this is not aviable. It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.

Thanks for your Time and sorry for my english.

EDIT: At least the read process works now and i loop trough a selected range. Here is the working code:

        public void writeExcelFile()
        {

            String inputFile = @"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";

            Excel.Application oXL = new Excel.Application();


#if DEBUG
            oXL.Visible = true;
            oXL.DisplayAlerts = true;
#else
                oXL.Visible = false; 
                oXL.DisplayAlerts = false;
#endif


            //Open the Excel File
            Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);

            String SheetName = "Gesamt";
            Excel._Worksheet oSheet = oWB.Sheets[SheetName];

            String start_range = "B4";
            String end_range = "R81";

            Object[,] values = oSheet.get_Range(start_range, end_range).Value2;

            int t = values.GetLength(0);
            for (int i = 1; i <= values.GetLength(0); i++)
            {
                String val = values[i, 1].ToString();
            }

            oXL.Quit();

        }

Solution

  • After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.

    the code:

            public void writeExcelFile()
            {
    
                try
                {
    
                    String inputFile = @"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
    
                    Excel.Application oXL = new Excel.Application();
    
    
    #if DEBUG
                    oXL.Visible = true;
                    oXL.DisplayAlerts = true;
    #else
                    oXL.Visible = false; 
                    oXL.DisplayAlerts = false;
    #endif
    
    
                    //Open a Excel File
                    Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
                    Excel._Worksheet oSheet = oWB.ActiveSheet;
    
                    List<String> Name = new List<String>();
                    List<Double> Percentage = new List<Double>();
    
                    Name.Add("Anil");
                    Name.Add("Vikas");
                    Name.Add("Ashwini");
                    Name.Add("Tobias");
                    Name.Add("Stuti");
                    Name.Add("Raghavendra");
                    Name.Add("Chithra");
                    Name.Add("Glen");
                    Name.Add("Darren");
                    Name.Add("Michael");
    
    
                    Percentage.Add(78.5);
                    Percentage.Add(65.3);
                    Percentage.Add(56);
                    Percentage.Add(56);
                    Percentage.Add(97);
                    Percentage.Add(89);
                    Percentage.Add(85);
                    Percentage.Add(76);
                    Percentage.Add(78);
                    Percentage.Add(89);
    
                    oSheet.Cells[1, 1] = "Name";
                    oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
    
    
                    //Enter the Header data in Column A
                    int i = 0;
                    for (i = 0; i < Name.Count; i++)
                    {
                        oSheet.Cells[i + 2, 1] = Name[i];
                    }
    
                    //Enter the Percentage data in Column B
                    for (i = 0; i < Percentage.Count; i++)
                    {
                        oSheet.Cells[i + 2, 2] = Percentage[i];
                    }
    
                    oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
                    //Obtain the Average of the Percentage Data
                    string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
    
                    oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
    
                    //Format the Header row to make it Bold and blue
                    oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
                    oSheet.get_Range("A1", "B1").Font.Bold = true;
                    //Set the column widthe of Column A and Column B to 20
                    oSheet.get_Range("A1", "B12").ColumnWidth = 20;
    
                    //String ReportFile = @"D:\Excel\Output.xls";
                    oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
                                            Type.Missing, Type.Missing,
                                            false,
                                            false,
                                            Excel.XlSaveAsAccessMode.xlNoChange,
                                            Type.Missing,
                                            Type.Missing,
                                            Type.Missing,
                                            Type.Missing,
                                            Type.Missing);
    
    
                    oXL.Quit();
    
                    Marshal.ReleaseComObject(oSheet);
                    Marshal.ReleaseComObject(oWB);
                    Marshal.ReleaseComObject(oXL);
    
                    oSheet = null;
                    oWB = null;
                    oXL = null;
                    GC.GetTotalMemory(false);
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.GetTotalMemory(true);
                }
                catch (Exception ex)
                {
                    String errorMessage = "Error reading the Excel file : " + ex.Message;
                    MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
    
            }
    

    This is not my own code its from a blog: the blog where i got it just edited so it works for me.