Excel C#输入特定单元格

时间:2011-09-13 16:49:29

标签: c# excel

我正在尝试使用C#自动将数字“6”放入单元格“F6”中。我一直在寻找,我找不到直接的答案。我已经在我的C#表单中引用了excel。非常感谢任何帮助

using Excel = Microsoft.Office.Interop.Excel;

2 个答案:

答案 0 :(得分:2)

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

其他有价值的资源可以在this question找到。

答案 1 :(得分:1)

这是我编写的用于加载数据库视图的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);
        }
    }