Excel c#输入到特定单元格

本文关键字:单元格 输入 Excel | 更新日期: 2023-09-27 18:08:33

我正试图让excel使用c#自动将数字"6"放入单元格"F6"。我到处都找遍了,就是找不到一个直接的答案。我已经在c#表单中引用了excel。非常感谢您的帮助

using Excel = Microsoft.Office.Interop.Excel;

Excel c#输入到特定单元格

摘自在线文档:

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";

在这个问题中可以找到其他有价值的资源。

下面是我编写的用于加载数据库视图的excel插件的代码片段。如果您想将数据插入到一个单元格中扩展到插入多行数据,那么它有一个重要的优化。

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