开发者

Excel C# inputting into specific cell

开发者 https://www.devze.com 2023-04-04 19:37 出处:网络
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 alr开发

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 alr开发者_开发知识库eady. 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);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消