简体   繁体   中英

Excel C# inputting into specific cell

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;

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 .

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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM