使用C#在新Excel工作表.net中插入表

时间:2015-10-29 10:28:46

标签: c# excel winforms

以下编写的代码适用于在已经存在的excel文件(D:\ MySamplefile.xls)中插入表及其值。

private void WriteToExcel()
{
    string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=D:\\MySamplefile.xls; Extended Properties=Excel 8.0;";
    using (OleDbConnection Connection = new OleDbConnection(connectionString))
    {
        Connection.Open();
        using (OleDbCommand command = new OleDbCommand())
        {
            command.Connection = Connection;
            command.CommandText = "CREATE TABLE [EMPLOYEE](EmpFirstName Char(100), EmpLastName char(100), EmpDept char(250))";
            command.ExecuteNonQuery();
        }

        //Add values to the table (EMPTable) in the Worksheet
        string strSql = "INSERT INTO EMPLOYEE (EmpFirstName, EmpLastName, [EmpDept]) VALUES (?, ?, ?)";
        using (OleDbCommand dbCmd = new OleDbCommand(strSql, Connection))
        {
            dbCmd.CommandType = CommandType.Text;
            dbCmd.Parameters.AddWithValue("EmpFirstName", "xyz");
            dbCmd.Parameters.AddWithValue("EmpLastName", "abc");
            dbCmd.Parameters.AddWithValue("[EmpDept]", "pqr");
            dbCmd.ExecuteNonQuery();
        }
    }   
}

我的要求是,我需要在新创建的excel工作表上编写相同的内容,该工作表未保存任何位置。对于下面给出的新的Excel文档创建代码。

    public void createExcelDoc( int rowHeight,int sizeCol1, int sizeCol2)
{
        app = new Application();
        app.Visible = true;
        workbook = app.Workbooks.Add(1);
        worksheet = (Worksheet)workbook.Sheets[1];
        worksheet.Columns[1].ColumnWidth = 5;
        worksheet.Rows.RowHeight = rowHeight;               
        worksheet.Columns[2].ColumnWidth = sizeCol1;
        worksheet.Columns[3].ColumnWidth = sizeCol2;                
        workbook.Windows.Application.WindowState = XlWindowState.xlMaximized;            
}

我需要将WriteToExcel()方法Data Source=D:\\MySamplefile.xls;中的connectionString替换为其他东西。我不知道。

1 个答案:

答案 0 :(得分:2)

您可以通过OleDb连接到Excel,就像使用Access一样。连接字符串示例可在此处找到:

https://www.connectionstrings.com/excel/

为清楚起见,旧的(.xls)文件看起来像这样:

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
    @"Data Source=D:\MySamplefile.xls;Extended Properties=Excel 8.0;";

但是,对于你的方法来说,这似乎有点过分。数据从哪里插入到Excel中?可能有更好(和更简单)的方法来做到这一点。