0

I am trying to just get excel to put the Number "6" into cell "F6" automatically using C#. I have been looking all over and I can't find a straight answer. I referenced excel in my C# form already. Any help is greatly appreciated

using Excel = Microsoft.Office.Interop.Excel;
Russell Saari
  • 985
  • 11
  • 26
  • 41

2 Answers2

2

Cribbed from the online documentation:

var xl = new Excel.Application();
xl.Visible = true;
var wb = (Excel._Workbook)(xl.Workbooks.Add(Missing.Value));
var sheet = (Excel._Worksheet)wb.ActiveSheet;
sheet.Cells[6, 6] = "6";

Other valuable resources can be found in this question.

Community
  • 1
  • 1
Ben Hoffstein
  • 102,129
  • 8
  • 104
  • 120
  • Thank you that worked out really well actually so well that if pretty much finished the program I am writing. Seriously appreciate the help!!! – Russell Saari Sep 13 '11 at 21:04
2

Here's a snippet of code from the excel plugin I wrote to load database views. It's got an important optimization if you want to extend from inserting data into one cell to inserting multiple rows of data.

    private void Fill()
    {
        if (string.IsNullOrEmpty(CurrConnectionStr)) return;

        SelectedTable = TableComboBox.Text;

        if (string.IsNullOrEmpty(SelectedTable)) return;

        try
        {
            Globals.ThisAddIn.Application.Cells.ClearContents();
            var dataTable = new System.Data.DataTable(); 
            var query = string.Format(RowsQuery, SelectedTable);
            using (var sqlDataAdapter = new SqlDataAdapter(query, CurrConnectionStr))
            {
                sqlDataAdapter.Fill(dataTable);
            }
            var excelApplicationObject = Globals.ThisAddIn.Application;
            int rowNumber = 1;
            foreach (System.Data.DataColumn column in dataTable.Columns)
            {
                int columnNumber = dataTable.Columns.IndexOf(column) + 1;
                excelApplicationObject.Cells[rowNumber, columnNumber].Value2 = column.ColumnName;
            }
            rowNumber += 1;
            foreach (System.Data.DataRow row in dataTable.Rows)
            {
                excelApplicationObject
                    .Cells
                    .Range[
                        excelApplicationObject.Cells[rowNumber, 1], 
                        excelApplicationObject.Cells[rowNumber, row.ItemArray.Count()]]
                    .Value2 = row.ItemArray;

                rowNumber++;
            }
            excelApplicationObject.Cells[rowNumber, 1] = "View Name: ";
            excelApplicationObject.Cells[rowNumber, 2] = SelectedTable;
            rowNumber += 1;
            excelApplicationObject.Cells[rowNumber, 1] = "Saved At:";
            excelApplicationObject.Cells[rowNumber, 2] = DateTime.Now.ToLongTimeString();
            rowNumber += 1;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121