1

I'm trying to write Excel application-level add-in. It makes SQL query to the database and populates worksheet with its results. I thought, it should be simple... But not. Is there any way to insert DataTable into excel worksheet? Something like this:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    string cmdString = "SELECT * FROM [Table];" // Simplifyed query, in my add-in I need to JOIN 3 tables
    SqlCommand cmd = new SqlCommand(cmdString, connection);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda.Fill(dt);

    // What I need to write here to insert my DataTable contents into worksheet?
}

Maybe, I should use another approach (not DataTable)? However, my query can return up to 100000 rows of data with 4 columns. So, cell-by-cell pasting will not work, I think.

4

1 回答 1

0

如果您准备跳过几圈,那么 CopyFromRecordset 是我见过的最快的处理方法:

http://msdn.microsoft.com/en-us/library/office/ff839240(v=office.15).aspx

我可以使用 CopyFromRecordset 在几秒钟内将一百万行从 SQL Server 填充到 Excel 中。

基本上,您需要创建一个记录集而不是数据表,并且您需要使用 ADO(或 DAO)。就我个人而言,我喜欢将此代码与其他所有代码分开,并且仅将 ADO 用于此功能,因为它具有固有的弱点。例如,您不能将“使用”与 ADO 连接等一起使用。

这是一个更完整的示例(在 VB 中,但很容易更改为 C#):

http://support.microsoft.com/kb/246335/

于 2014-10-29T12:23:15.623 回答