概述
最常用于向 excel 工作簿传输数据的技术是自动化。利用“自动化”,您可以调用特定于 excel 任务的方法和属性。“自动化”给您提供了指定数据在工作簿中所处的位置、将工作簿格式化以及在运行时进行各种设置的最大的灵活性。
利用“自动化”,您可以使用多种技术来传输数据:
| • | 逐个单元格地传输数据 |
| • | 将数组中的数据传输到由单元格组成的区域。 |
| • | 使用 copyfromrecordset 方法向单元格区域传输 ado 记录集中的数据。 |
| • | 在 excel 工作表上创建一个 querytable 对象,该对象包含对 odbc 或 oledb 数据源进行查询的结果。 |
| • | 将数据传输到剪贴板,然后将剪贴板内容粘贴到 excel 工作表中。 |
还可以使用多种未必需要利用“自动化”来向 excel 传输数据的方法。如果您正在运行服务器端程序,这可以是一种将批量数据处理从客户端移走的好方法。
要在不使用“自动化”的情况下传输数据,您可以使用下列方法:
| • | 将数据传输到制表符分隔的或逗号分隔的文本文件,然后 excel 可以将该文本文件分析为工作表上的单元格。 |
| • | 使用 ado.net 将数据传输到工作表。 |
| • | 将 xml 数据传输到 excel(仅限于 2002 和 2003 版)以提供可以被格式化和排列为行和列的数据。 |
方法
使用“自动化”逐个单元格地传输数据
利用“自动化”,您可以逐个单元格地向工作表传输数据:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// add data to cells in the first worksheet in the new workbook.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange.value = "last name";
m_objrange = m_objsheet.get_range("b1", m_objopt);
m_objrange.value = "first name";
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.value = "doe";
m_objrange = m_objsheet.get_range("b2", m_objopt);
m_objrange.value = "john";
// apply bold to cells a1:b1.
m_objrange = m_objsheet.get_range("a1", "b1");
m_objfont = m_objrange.font;
m_objfont.bold=true;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book1.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
如果您具有少量的数据,则逐个单元格地传输数据是可以接受的方法。您可以灵活地将数据放到工作簿中的任何地方,并可以在运行时根据条件对单元格进行格式设置。然而,如果您具有大量需要传输到 excel 工作簿的数据,则使用这种方法不是一个好主意。您在运行时获取的每一个 range 对象都会产生一个接口请求,这意味着数据传输速度会变得较慢。此外,microsoft windows 95、microsoft windows 98 以及 microsoft windows millennium edition (me) 都对接口请求有 64 kb 的限制。如果您具有 64 kb 以上的接口请求,则“自动化”服务器 (excel) 可能会停止响应,或者您可能会收到指出内存不足的错误信息。有关其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// add data to cells in the first worksheet in the new workbook.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange.value = "last name";
m_objrange = m_objsheet.get_range("b1", m_objopt);
m_objrange.value = "first name";
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.value = "doe";
m_objrange = m_objsheet.get_range("b2", m_objopt);
m_objrange.value = "john";
// apply bold to cells a1:b1.
m_objrange = m_objsheet.get_range("a1", "b1");
m_objfont = m_objrange.font;
m_objfont.bold=true;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book1.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
如果您具有少量的数据,则逐个单元格地传输数据是可以接受的方法。您可以灵活地将数据放到工作簿中的任何地方,并可以在运行时根据条件对单元格进行格式设置。然而,如果您具有大量需要传输到 excel 工作簿的数据,则使用这种方法不是一个好主意。您在运行时获取的每一个 range 对象都会产生一个接口请求,这意味着数据传输速度会变得较慢。此外,microsoft windows 95、microsoft windows 98 以及 microsoft windows millennium edition (me) 都对接口请求有 64 kb 的限制。如果您具有 64 kb 以上的接口请求,则“自动化”服务器 (excel) 可能会停止响应,或者您可能会收到指出内存不足的错误信息。有关其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// add data to cells in the first worksheet in the new workbook.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange.value = "last name";
m_objrange = m_objsheet.get_range("b1", m_objopt);
m_objrange.value = "first name";
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.value = "doe";
m_objrange = m_objsheet.get_range("b2", m_objopt);
m_objrange.value = "john";
// apply bold to cells a1:b1.
m_objrange = m_objsheet.get_range("a1", "b1");
m_objfont = m_objrange.font;
m_objfont.bold=true;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book1.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
如果您具有少量的数据,则逐个单元格地传输数据是可以接受的方法。您可以灵活地将数据放到工作簿中的任何地方,并可以在运行时根据条件对单元格进行格式设置。然而,如果您具有大量需要传输到 excel 工作簿的数据,则使用这种方法不是一个好主意。您在运行时获取的每一个 range 对象都会产生一个接口请求,这意味着数据传输速度会变得较慢。此外,microsoft windows 95、microsoft windows 98 以及 microsoft windows millennium edition (me) 都对接口请求有 64 kb 的限制。如果您具有 64 kb 以上的接口请求,则“自动化”服务器 (excel) 可能会停止响应,或者您可能会收到指出内存不足的错误信息。有关其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
需要再次强调的是,逐个单元格地传输数据仅对少量数据而言才可以接受。如果您必须向 excel 传输大数据集,则应考虑使用本文中讨论的其他方法之一来批量地传输数据。
有关其他信息以及如何利用 visual c# .net 自动运行 excel 的示例,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
使用“自动化”将数据数组传输到工作表上的区域
可以将数据数组一次性地传输到由多个单元格组成的区域:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// create an array for the headers and add it to cells a1:c1.
object[] objheaders = {"order id", "amount", "tax"};
m_objrange = m_objsheet.get_range("a1", "c1");
m_objrange.value = objheaders;
m_objfont = m_objrange.font;
m_objfont.bold=true;
// create an array with 3 columns and 100 rows and add it to
// the worksheet starting at cell a2.
object[,] objdata = new object[100,3];
random rdm = new random((int)datetime.now.ticks);
double norderamt, ntax;
for(int r=0;r<100;r++)
{
objdata[r,0] = "ord" + r.tostring("0000");
norderamt = rdm.next(1000);
objdata[r,1] = norderamt.tostring("c");
ntax = norderamt*0.07;
objdata[r,2] = ntax.tostring("c");
}
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange = m_objrange.get_resize(100,3);
m_objrange.value = objdata;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book2.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
如果您使用数组而不是逐个单元格地传输数据,则在传输大量数据时,传输性能会大大地增强。请考虑前面代码中的下列几行,这些行将数据传输到工作表中的 300 个单元格:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// create an array for the headers and add it to cells a1:c1.
object[] objheaders = {"order id", "amount", "tax"};
m_objrange = m_objsheet.get_range("a1", "c1");
m_objrange.value = objheaders;
m_objfont = m_objrange.font;
m_objfont.bold=true;
// create an array with 3 columns and 100 rows and add it to
// the worksheet starting at cell a2.
object[,] objdata = new object[100,3];
random rdm = new random((int)datetime.now.ticks);
double norderamt, ntax;
for(int r=0;r<100;r++)
{
objdata[r,0] = "ord" + r.tostring("0000");
norderamt = rdm.next(1000);
objdata[r,1] = norderamt.tostring("c");
ntax = norderamt*0.07;
objdata[r,2] = ntax.tostring("c");
}
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange = m_objrange.get_resize(100,3);
m_objrange.value = objdata;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book2.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
如果您使用数组而不是逐个单元格地传输数据,则在传输大量数据时,传输性能会大大地增强。请考虑前面代码中的下列几行,这些行将数据传输到工作表中的 300 个单元格:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// create an array for the headers and add it to cells a1:c1.
object[] objheaders = {"order id", "amount", "tax"};
m_objrange = m_objsheet.get_range("a1", "c1");
m_objrange.value = objheaders;
m_objfont = m_objrange.font;
m_objfont.bold=true;
// create an array with 3 columns and 100 rows and add it to
// the worksheet starting at cell a2.
object[,] objdata = new object[100,3];
random rdm = new random((int)datetime.now.ticks);
double norderamt, ntax;
for(int r=0;r<100;r++)
{
objdata[r,0] = "ord" + r.tostring("0000");
norderamt = rdm.next(1000);
objdata[r,1] = norderamt.tostring("c");
ntax = norderamt*0.07;
objdata[r,2] = ntax.tostring("c");
}
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange = m_objrange.get_resize(100,3);
m_objrange.value = objdata;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book2.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
如果您使用数组而不是逐个单元格地传输数据,则在传输大量数据时,传输性能会大大地增强。请考虑前面代码中的下列几行,这些行将数据传输到工作表中的 300 个单元格:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
objrange = objsheet.get_range("a2", m_objopt);
objrange = objrange.get_resize(100,3);
objrange.value = objdata;
这些代码代表了两个接口请求:一个请求是针对 range 方法返回的 range 对象,另一个请求是针对 resize 方法返回的 range 对象。相比之下,逐个单元格地传输数据却需要对 range 对象发出 300 个接口请求。只要有可能,您就可以从批量地传输数据以及减少所发出的接口请求的数量当中受益。
有关通过 excel 自动化并使用数组获取和设置区域中的值的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
使用“自动化”将 ado 记录集传输到工作表区域
excel 2000、excel 2002 和 excel 2003 的对象模型提供了 copyfromrecordset 方法,用于向工作表上的区域传输 ado 记录集。下面的代码说明了如何使用 copyfromrecordset 方法使 excel 自动运行,以传输 northwind 示例数据库中的“订单”表的内容:
// create a recordset from all the records in the orders table.
adodb.connection objconn = new adodb.connection();
adodb._recordset objrs = null;
objconn.open("provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", "", "", 0);
objconn.cursorlocation = adodb.cursorlocationenum.aduseclient;
object objrecaff;
objrs = (adodb._recordset)objconn.execute("orders", out objrecaff,
(int)adodb.commandtypeenum.adcmdtable);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// get the fields collection from the recordset and determine
// the number of fields (or columns).
system.collections.ienumerator objfields = objrs.fields.getenumerator();
int nfields = objrs.fields.count;
// create an array for the headers and add it to the
// worksheet starting at cell a1.
object[] objheaders = new object[nfields];
adodb.field objfield = null;
for(int n=0;n<nfields;n++)
{
objfields.movenext();
objfield = (adodb.field)objfields.current;
objheaders[n] = objfield.name;
}
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange = m_objrange.get_resize(1, nfields);
m_objrange.value = objheaders;
m_objfont = m_objrange.font;
m_objfont.bold=true;
// transfer the recordset to the worksheet starting at cell a2.
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.copyfromrecordset(objrs, m_objopt, m_objopt);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book3.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// close the recordset and connection.
objrs.close();
objconn.close();
注意:copyfromrecordset 只能与 ado recordset 对象一起使用。使用 ado.net 创建的 dataset 不能与 copyfromrecordset 方法一起使用。以下几部分中的多个示例演示了如何利用 ado.net 向 excel 传输数据。
// create a recordset from all the records in the orders table.
adodb.connection objconn = new adodb.connection();
adodb._recordset objrs = null;
objconn.open("provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", "", "", 0);
objconn.cursorlocation = adodb.cursorlocationenum.aduseclient;
object objrecaff;
objrs = (adodb._recordset)objconn.execute("orders", out objrecaff,
(int)adodb.commandtypeenum.adcmdtable);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// get the fields collection from the recordset and determine
// the number of fields (or columns).
system.collections.ienumerator objfields = objrs.fields.getenumerator();
int nfields = objrs.fields.count;
// create an array for the headers and add it to the
// worksheet starting at cell a1.
object[] objheaders = new object[nfields];
adodb.field objfield = null;
for(int n=0;n<nfields;n++)
{
objfields.movenext();
objfield = (adodb.field)objfields.current;
objheaders[n] = objfield.name;
}
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange = m_objrange.get_resize(1, nfields);
m_objrange.value = objheaders;
m_objfont = m_objrange.font;
m_objfont.bold=true;
// transfer the recordset to the worksheet starting at cell a2.
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.copyfromrecordset(objrs, m_objopt, m_objopt);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book3.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// close the recordset and connection.
objrs.close();
objconn.close();
注意:copyfromrecordset 只能与 ado recordset 对象一起使用。使用 ado.net 创建的 dataset 不能与 copyfromrecordset 方法一起使用。以下几部分中的多个示例演示了如何利用 ado.net 向 excel 传输数据。
// create a recordset from all the records in the orders table.
adodb.connection objconn = new adodb.connection();
adodb._recordset objrs = null;
objconn.open("provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", "", "", 0);
objconn.cursorlocation = adodb.cursorlocationenum.aduseclient;
object objrecaff;
objrs = (adodb._recordset)objconn.execute("orders", out objrecaff,
(int)adodb.commandtypeenum.adcmdtable);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// get the fields collection from the recordset and determine
// the number of fields (or columns).
system.collections.ienumerator objfields = objrs.fields.getenumerator();
int nfields = objrs.fields.count;
// create an array for the headers and add it to the
// worksheet starting at cell a1.
object[] objheaders = new object[nfields];
adodb.field objfield = null;
for(int n=0;n<nfields;n++)
{
objfields.movenext();
objfield = (adodb.field)objfields.current;
objheaders[n] = objfield.name;
}
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange = m_objrange.get_resize(1, nfields);
m_objrange.value = objheaders;
m_objfont = m_objrange.font;
m_objfont.bold=true;
// transfer the recordset to the worksheet starting at cell a2.
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.copyfromrecordset(objrs, m_objopt, m_objopt);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book3.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// close the recordset and connection.
objrs.close();
objconn.close();
注意:copyfromrecordset 只能与 ado recordset 对象一起使用。使用 ado.net 创建的 dataset 不能与 copyfromrecordset 方法一起使用。以下几部分中的多个示例演示了如何利用 ado.net 向 excel 传输数据。
使用“自动化”在工作表上创建 querytable 对象
querytable 对象代表了一个表,该表是用从外部数据源返回的数据生成的。当您自动运行 excel 时,可以通过提供指向 ole db 或 odbc 数据源的连接字符串和 sql 字符串来创建 querytable。excel 将生成记录集并将该记录集插入到工作表中您所指定的位置。querytable 对象提供了下列优于 copyfromrecordset 方法的优点:
| • | excel 处理记录集的创建并将其放置到工作表中。 |
| • | 您可以利用 querytable 对象保存查询,并在以后刷新它以获取更新的记录集。 |
| • | 当向工作表中添加新的 querytable 时,可以指定将工作表上的单元格中已经存在的数据移位,以处理新数据(有关详细信息,请查看 refreshstyle 属性)。 |
下面的代码演示了如何自动运行 excel 2000、excel 2002 或 excel 2003,以便使用 northwind 示例数据库中的数据在 excel 工作表中创建新的 querytable:
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// create a querytable that starts at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objqrytables = m_objsheet.querytables;
m_objqrytable = (excel._querytable)m_objqrytables.add(
"oledb;provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", m_objrange, "select * from orders");
m_objqrytable.refreshstyle = excel.xlcellinsertionmode.xlinsertentirerows;
m_objqrytable.refresh(false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book4.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// create a querytable that starts at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objqrytables = m_objsheet.querytables;
m_objqrytable = (excel._querytable)m_objqrytables.add(
"oledb;provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", m_objrange, "select * from orders");
m_objqrytable.refreshstyle = excel.xlcellinsertionmode.xlinsertentirerows;
m_objqrytable.refresh(false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book4.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// create a querytable that starts at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objqrytables = m_objsheet.querytables;
m_objqrytable = (excel._querytable)m_objqrytables.add(
"oledb;provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", m_objrange, "select * from orders");
m_objqrytable.refreshstyle = excel.xlcellinsertionmode.xlinsertentirerows;
m_objqrytable.refresh(false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book4.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
使用 windows 剪贴板
可以使用 windows 剪贴板来向工作表传输数据。要将数据粘贴到工作表上的多个单元格中,可以复制具有以下格式的字符串:在该字符串中,列由制表符分隔,行由回车符分隔。下面的代码说明了 visual c# .net 如何使用 windows 剪贴板来向 excel 中传输数据:
// copy a string to the windows clipboard.
string sdata = "firstname\tlastname\tbirthdate\r\n" +
"bill\tbrown\t2/5/85\r\n" +
"joe\tthomas\t1/1/91";
system.windows.forms.clipboard.setdataobject(sdata);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// paste the data starting at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objsheet.paste(m_objrange, false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book5.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// copy a string to the windows clipboard.
string sdata = "firstname\tlastname\tbirthdate\r\n" +
"bill\tbrown\t2/5/85\r\n" +
"joe\tthomas\t1/1/91";
system.windows.forms.clipboard.setdataobject(sdata);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// paste the data starting at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objsheet.paste(m_objrange, false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book5.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
// copy a string to the windows clipboard.
string sdata = "firstname\tlastname\tbirthdate\r\n" +
"bill\tbrown\t2/5/85\r\n" +
"joe\tthomas\t1/1/91";
system.windows.forms.clipboard.setdataobject(sdata);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// paste the data starting at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objsheet.paste(m_objrange, false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book5.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
创建可由 excel 分析为行和列的带分隔符的文本文件
excel 可以打开由制表符或逗号分隔的文件并正确地将数据分析为单元格。当您希望向工作表传输大量数据而只使用少量(如果有的话)自动化功能时,可以使用此功能。这对于客户端-服务器程序而言可能是一个好方法,因为文本文件可以在服务器端生成。然后,可以在客户端根据需要使用“自动化”来打开文本文件。
下面的代码说明了如何从利用 ado.net 读取的数据生成制表符分隔的文本文件:
// connect to the data source.
system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection(
"provider=microsoft.jet.oledb.4.0;data source=" + m_strnorthwind + ";");
objconn.open();
// execute a command to retrieve all records from the employees table.
system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(
"select * from employees", objconn);
system.data.oledb.oledbdatareader objreader;
objreader = objcmd.executereader();
// create the filestream and streamwriter object to write
// the recordset contents to file.
system.io.filestream fs = new system.io.filestream(
m_strsamplefolder + "book6.txt", system.io.filemode.create);
system.io.streamwriter sw = new system.io.streamwriter(
fs, system.text.encoding.unicode);
// write the field names (headers) as the first line in the text file.
sw.writeline(objreader.getname(0) + "\t" + objreader.getname(1) +
"\t" + objreader.getname(2) + "\t" + objreader.getname(3) +
"\t" + objreader.getname(4) + "\t" + objreader.getname(5));
// write the first six columns in the recordset to a text file as
// tab-delimited.
while(objreader.read())
{
for(int i=0;i<=5;i++)
{
if(!objreader.isdbnull(i))
{
string s;
s = objreader.getdatatypename(i);
if(objreader.getdatatypename(i)=="dbtype_i4")
{
sw.write(objreader.getint32(i).tostring());
}
else if(objreader.getdatatypename(i)=="dbtype_date")
{
sw.write(objreader.getdatetime(i).tostring("d"));
}
else if (objreader.getdatatypename(i)=="dbtype_wvarchar")
{
sw.write(objreader.getstring(i));
}
}
if(i<5) sw.write("\t");
}
sw.writeline();
}
sw.flush(); // write the buffered data to the filestream.
// close the filestream.
fs.close();
// close the reader and the connection.
objreader.close();
objconn.close();
上述代码没有使用自动化。然而,如果您愿意,您可以按如下方式使用“自动化”来打开文本文件,并以 excel 工作簿格式保存该文件:
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
// connect to the data source.
system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection(
"provider=microsoft.jet.oledb.4.0;data source=" + m_strnorthwind + ";");
objconn.open();
// execute a command to retrieve all records from the employees table.
system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(
"select * from employees", objconn);
system.data.oledb.oledbdatareader objreader;
objreader = objcmd.executereader();
// create the filestream and streamwriter object to write
// the recordset contents to file.
system.io.filestream fs = new system.io.filestream(
m_strsamplefolder + "book6.txt", system.io.filemode.create);
system.io.streamwriter sw = new system.io.streamwriter(
fs, system.text.encoding.unicode);
// write the field names (headers) as the first line in the text file.
sw.writeline(objreader.getname(0) + "\t" + objreader.getname(1) +
"\t" + objreader.getname(2) + "\t" + objreader.getname(3) +
"\t" + objreader.getname(4) + "\t" + objreader.getname(5));
// write the first six columns in the recordset to a text file as
// tab-delimited.
while(objreader.read())
{
for(int i=0;i<=5;i++)
{
if(!objreader.isdbnull(i))
{
string s;
s = objreader.getdatatypename(i);
if(objreader.getdatatypename(i)=="dbtype_i4")
{
sw.write(objreader.getint32(i).tostring());
}
else if(objreader.getdatatypename(i)=="dbtype_date")
{
sw.write(objreader.getdatetime(i).tostring("d"));
}
else if (objreader.getdatatypename(i)=="dbtype_wvarchar")
{
sw.write(objreader.getstring(i));
}
}
if(i<5) sw.write("\t");
}
sw.writeline();
}
sw.flush(); // write the buffered data to the filestream.
// close the filestream.
fs.close();
// close the reader and the connection.
objreader.close();
objconn.close();
上述代码没有使用自动化。然而,如果您愿意,您可以按如下方式使用“自动化”来打开文本文件,并以 excel 工作簿格式保存该文件:
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
// connect to the data source.
system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection(
"provider=microsoft.jet.oledb.4.0;data source=" + m_strnorthwind + ";");
objconn.open();
// execute a command to retrieve all records from the employees table.
system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(
"select * from employees", objconn);
system.data.oledb.oledbdatareader objreader;
objreader = objcmd.executereader();
// create the filestream and streamwriter object to write
// the recordset contents to file.
system.io.filestream fs = new system.io.filestream(
m_strsamplefolder + "book6.txt", system.io.filemode.create);
system.io.streamwriter sw = new system.io.streamwriter(
fs, system.text.encoding.unicode);
// write the field names (headers) as the first line in the text file.
sw.writeline(objreader.getname(0) + "\t" + objreader.getname(1) +
"\t" + objreader.getname(2) + "\t" + objreader.getname(3) +
"\t" + objreader.getname(4) + "\t" + objreader.getname(5));
// write the first six columns in the recordset to a text file as
// tab-delimited.
while(objreader.read())
{
for(int i=0;i<=5;i++)
{
if(!objreader.isdbnull(i))
{
string s;
s = objreader.getdatatypename(i);
if(objreader.getdatatypename(i)=="dbtype_i4")
{
sw.write(objreader.getint32(i).tostring());
}
else if(objreader.getdatatypename(i)=="dbtype_date")
{
sw.write(objreader.getdatetime(i).tostring("d"));
}
else if (objreader.getdatatypename(i)=="dbtype_wvarchar")
{
sw.write(objreader.getstring(i));
}
}
if(i<5) sw.write("\t");
}
sw.writeline();
}
sw.flush(); // write the buffered data to the filestream.
// close the filestream.
fs.close();
// close the reader and the connection.
objreader.close();
objconn.close();
上述代码没有使用自动化。然而,如果您愿意,您可以按如下方式使用“自动化”来打开文本文件,并以 excel 工作簿格式保存该文件:
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
// open the text file in excel. m_objexcel = new excel.application(); m_objbooks = (excel.workbooks)m_objexcel.workbooks; m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1, excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote, false, true, false, false, false, false, m_objopt, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook = m_objexcel.activeworkbook; // save the text file in the typical workbook format and quit excel. m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal, m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt, m_objopt, m_objopt); m_objbook.close(false, m_objopt, m_objopt); m_objexcel.quit();
使用 ado.net 将数据传输到工作表
您可以使用 microsoft jet ole db 提供程序向现有 excel 工作簿中的表中添加记录。excel 中的表 只是由单元格组成的区域;该区域可能具有规定的名称。通常,区域的第一行包含标题(或字段名),该区域中所有以后的行都包含记录。
下面的代码向 book7.xls 中的表添加了两个新记录。在此情况下,该表是 sheet1:
// establish a connection to the data source. system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection( "provider=microsoft.jet.oledb.4.0;data source=" + m_strsamplefolder + "book7.xls;extended properties=excel 8.0;"); objconn.open(); // add two records to the table named mytable. system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(); objcmd.connection = objconn; objcmd.commandtext = "insert into mytable (firstname, lastname)" + " values (bill, brown)"; objcmd.executenonquery(); objcmd.commandtext = "insert into mytable (firstname, lastname)" + " values (joe, thomas)"; objcmd.executenonquery(); // close the connection. objconn.close();
当您按本例所示的方法利用 ado.net 添加记录时,工作簿中的格式将被保持。添加到行中的每个记录都将继承它前面的行的格式。
有关使用 ado.net 的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
// establish a connection to the data source. system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection( "provider=microsoft.jet.oledb.4.0;data source=" + m_strsamplefolder + "book7.xls;extended properties=excel 8.0;"); objconn.open(); // add two records to the table named mytable. system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(); objcmd.connection = objconn; objcmd.commandtext = "insert into mytable (firstname, lastname)" + " values (bill, brown)"; objcmd.executenonquery(); objcmd.commandtext = "insert into mytable (firstname, lastname)" + " values (joe, thomas)"; objcmd.executenonquery(); // close the connection. objconn.close();
当您按本例所示的方法利用 ado.net 添加记录时,工作簿中的格式将被保持。添加到行中的每个记录都将继承它前面的行的格式。
有关使用 ado.net 的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
// establish a connection to the data source. system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection( "provider=microsoft.jet.oledb.4.0;data source=" + m_strsamplefolder + "book7.xls;extended properties=excel 8.0;"); objconn.open(); // add two records to the table named mytable. system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(); objcmd.connection = objconn; objcmd.commandtext = "insert into mytable (firstname, lastname)" + " values (bill, brown)"; objcmd.executenonquery(); objcmd.commandtext = "insert into mytable (firstname, lastname)" + " values (joe, thomas)"; objcmd.executenonquery(); // close the connection. objconn.close();
当您按本例所示的方法利用 ado.net 添加记录时,工作簿中的格式将被保持。添加到行中的每个记录都将继承它前面的行的格式。
有关使用 ado.net 的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
有关如何将 jet oledb 提供程序与 excel 数据源一起使用的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章。
传输 xml 数据(excel 2002 和 excel 2003)
excel 2002 和 2003 可以打开格式完好的任何 xml 文件。您可以使用文件菜单上的打开命令直接打开 xml 文件,也可以使用 workbooks 集合的 open 或 openxml 方法以编程方式打开 xml 文件。如果您创建供在 excel 中使用的 xml 文件,您还可以创建样式表来设置数据的格式。
有关如何将 xml 与 excel 2002 一起使用的其他信息,请单击下面的文章编号,以查看 microsoft 知识库中相应的文章:
![]() |
回到顶端 |
创建完整的示例 visual c# .net 项目
| 1. | 创建一个名为 c:\exceldata 的新文件夹。示例程序将在此文件夹中存储 excel 工作簿。 | ||||||||||||
| 2. | 创建一个新工作簿,以供示例向其中写入数据:
|
||||||||||||
| 3. | 启动 visual studio .net。在文件菜单上,指向新建,然后单击项目。在 visual c# 项目下,选择 windows 应用程序。默认情况下会创建 form1。 | ||||||||||||
| 4. | 添加对 excel 对象库和 adodb 主 interop 程序集的引用。为此,请按照下列步骤操作:
|
||||||||||||
| 5. | 向 form1 添加一个 combo box 控件和一个 button 控件。 | ||||||||||||
| 6. | 为该窗体的 load 事件和 button 控件的 click 事件添加事件处理程序:
|
||||||||||||
| 7. | 在 form1.cs 中,将以下代码:
private void form1_load(object sender, system.eventargs e)
{
}
private void button1_click(object sender, system.eventargs e)
{
}
替换为: // excel object references.
private excel.application m_objexcel = null;
private excel.workbooks m_objbooks = null;
private excel._workbook m_objbook = null;
private excel.sheets m_objsheets = null;
private excel._worksheet m_objsheet = null;
private excel.range m_objrange = null;
private excel.font m_objfont = null;
private excel.querytables m_objqrytables = null;
private excel._querytable m_objqrytable = null;
// frequenty-used variable for optional arguments.
private object m_objopt = system.reflection.missing.value;
// paths used by the sample code for accessing and storing data.
private object m_strsamplefolder = "c:\\exceldata\\";
private string m_strnorthwind = "c:\\program files\\microsoft office\\office10\\samples\\northwind.mdb";
private void form1_load(object sender, system.eventargs e)
{
combobox1.dropdownstyle = comboboxstyle.dropdownlist;
combobox1.items.addrange(new object[]{
"use automation to transfer data cell by cell ",
"use automation to transfer an array of data to a range on a worksheet ",
"use automation to transfer an ado recordset to a worksheet range ",
"use automation to create a querytable on a worksheet",
"use the clipboard",
"create a delimited text file that excel can parse into rows and columns",
"transfer data to a worksheet using ado.net "});
combobox1.selectedindex = 0;
button1.text = "go!";
}
private void button1_click(object sender, system.eventargs e)
{
switch (combobox1.selectedindex)
{
case 0 : automation_cellbycell(); break;
case 1 : automation_usearray(); break;
case 2 : automation_adorecordset(); break;
case 3 : automation_querytable(); break;
case 4 : use_clipboard(); break;
case 5 : create_textfile(); break;
case 6 : use_adonet(); break;
}
//clean-up
m_objfont = null;
m_objrange = null;
m_objsheet = null;
m_objsheets = null;
m_objbooks = null;
m_objbook = null;
m_objexcel = null;
gc.collect();
}
private void automation_cellbycell()
{
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// add data to cells of the first worksheet in the new workbook.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange.set_value(m_objopt,"last name");
m_objrange = m_objsheet.get_range("b1", m_objopt);
m_objrange.set_value(m_objopt,"first name");
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.set_value(m_objopt,"doe");
m_objrange = m_objsheet.get_range("b2", m_objopt);
m_objrange.set_value(m_objopt,"john");
// apply bold to cells a1:b1.
m_objrange = m_objsheet.get_range("a1", "b1");
m_objfont = m_objrange.font;
m_objfont.bold=true;
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book1.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
}
private void automation_usearray()
{
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// create an array for the headers and add it to cells a1:c1.
object[] objheaders = {"order id", "amount", "tax"};
m_objrange = m_objsheet.get_range("a1", "c1");
m_objrange.set_value(m_objopt,objheaders);
m_objfont = m_objrange.font;
m_objfont.bold=true;
// create an array with 3 columns and 100 rows and add it to
// the worksheet starting at cell a2.
object[,] objdata = new object[100,3];
random rdm = new random((int)datetime.now.ticks);
double norderamt, ntax;
for(int r=0;r<100;r++)
{
objdata[r,0] = "ord" + r.tostring("0000");
norderamt = rdm.next(1000);
objdata[r,1] = norderamt.tostring("c");
ntax = norderamt*0.07;
objdata[r,2] = ntax.tostring("c");
}
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange = m_objrange.get_resize(100,3);
m_objrange.set_value(m_objopt,"objdata");
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book2.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
}
private void automation_adorecordset()
{
// create a recordset from all the records in the orders table.
adodb.connection objconn = new adodb.connection();
adodb._recordset objrs = null;
objconn.open("provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", "", "", 0);
objconn.cursorlocation = adodb.cursorlocationenum.aduseclient;
object objrecaff;
objrs = (adodb._recordset)objconn.execute("orders", out objrecaff,
(int)adodb.commandtypeenum.adcmdtable);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
// get the fields collection from the recordset and determine
// the number of fields (or columns).
system.collections.ienumerator objfields = objrs.fields.getenumerator();
int nfields = objrs.fields.count;
// create an array for the headers and add it to the
// worksheet starting at cell a1.
object[] objheaders = new object[nfields];
adodb.field objfield = null;
for(int n=0;n<nfields;n++)
{
objfields.movenext();
objfield = (adodb.field)objfields.current;
objheaders[n] = objfield.name;
}
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objrange = m_objrange.get_resize(1, nfields);
m_objrange.set_value(m_objopt,objheaders);
m_objfont = m_objrange.font;
m_objfont.bold=true;
// transfer the recordset to the worksheet starting at cell a2.
m_objrange = m_objsheet.get_range("a2", m_objopt);
m_objrange.copyfromrecordset(objrs, m_objopt, m_objopt);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book3.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange,
m_objopt, m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
//close the recordset and connection
objrs.close();
objconn.close();
}
private void automation_querytable()
{
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// create a querytable that starts at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objqrytables = m_objsheet.querytables;
m_objqrytable = (excel._querytable)m_objqrytables.add(
"oledb;provider=microsoft.jet.oledb.4.0;data source=" +
m_strnorthwind + ";", m_objrange, "select * from orders");
m_objqrytable.refreshstyle = excel.xlcellinsertionmode.xlinsertentirerows;
m_objqrytable.refresh(false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book4.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
}
private void use_clipboard()
{
// copy a string to the clipboard.
string sdata = "firstname\tlastname\tbirthdate\r\n" +
"bill\tbrown\t2/5/85\r\n" +
"joe\tthomas\t1/1/91";
system.windows.forms.clipboard.setdataobject(sdata);
// start a new workbook in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbook = (excel._workbook)(m_objbooks.add(m_objopt));
// paste the data starting at cell a1.
m_objsheets = (excel.sheets)m_objbook.worksheets;
m_objsheet = (excel._worksheet)(m_objsheets.get_item(1));
m_objrange = m_objsheet.get_range("a1", m_objopt);
m_objsheet.paste(m_objrange, false);
// save the workbook and quit excel.
m_objbook.saveas(m_strsamplefolder + "book5.xls", m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
}
private void create_textfile()
{
// connect to the data source.
system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection(
"provider=microsoft.jet.oledb.4.0;data source=" + m_strnorthwind + ";");
objconn.open();
// execute a command to retrieve all records from the employees table.
system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand(
"select * from employees", objconn);
system.data.oledb.oledbdatareader objreader;
objreader = objcmd.executereader();
// create the filestream and streamwriter object to write
// the recordset contents to file.
system.io.filestream fs = new system.io.filestream(
m_strsamplefolder + "book6.txt", system.io.filemode.create);
system.io.streamwriter sw = new system.io.streamwriter(
fs, system.text.encoding.unicode);
// write the field names (headers) as the first line in the text file.
sw.writeline(objreader.getname(0) + "\t" + objreader.getname(1) +
"\t" + objreader.getname(2) + "\t" + objreader.getname(3) +
"\t" + objreader.getname(4) + "\t" + objreader.getname(5));
// write the first six columns in the recordset to a text file as
// tab-delimited.
while(objreader.read())
{
for(int i=0;i<=5;i++)
{
if(!objreader.isdbnull(i))
{
string s;
s = objreader.getdatatypename(i);
if(objreader.getdatatypename(i)=="dbtype_i4")
{
sw.write(objreader.getint32(i).tostring());
}
else if(objreader.getdatatypename(i)=="dbtype_date")
{
sw.write(objreader.getdatetime(i).tostring("d"));
}
else if (objreader.getdatatypename(i)=="dbtype_wvarchar")
{
sw.write(objreader.getstring(i));
}
}
if(i<5) sw.write("\t");
}
sw.writeline();
}
sw.flush(); // write the buffered data to the filestream.
// close the filestream.
fs.close();
// close the reader and the connection.
objreader.close();
objconn.close();
// ==================================================================
// optionally, automate excel to open the text file and save it in the
// excel workbook format.
// open the text file in excel.
m_objexcel = new excel.application();
m_objbooks = (excel.workbooks)m_objexcel.workbooks;
m_objbooks.opentext(m_strsamplefolder + "book6.txt", excel.xlplatform.xlwindows, 1,
excel.xltextparsingtype.xldelimited, excel.xltextqualifier.xltextqualifierdoublequote,
false, true, false, false, false, false, m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt, m_objopt, m_objopt);
m_objbook = m_objexcel.activeworkbook;
// save the text file in the typical workbook format and quit excel.
m_objbook.saveas(m_strsamplefolder + "book6.xls", excel.xlfileformat.xlworkbooknormal,
m_objopt, m_objopt, m_objopt, m_objopt, excel.xlsaveasaccessmode.xlnochange, m_objopt, m_objopt,
m_objopt, m_objopt, m_objopt);
m_objbook.close(false, m_objopt, m_objopt);
m_objexcel.quit();
}
private void use_adonet()
{
// establish a connection to the data source.
system.data.oledb.oledbconnection objconn = new system.data.oledb.oledbconnection(
"provider=microsoft.jet.oledb.4.0;data source=" + m_strsamplefolder +
"book7.xls;extended properties=excel 8.0;");
objconn.open();
// add two records to the table named mytable.
system.data.oledb.oledbcommand objcmd = new system.data.oledb.oledbcommand();
objcmd.connection = objconn;
objcmd.commandtext = "insert into mytable (firstname, lastname)" +
" values (bill, brown)";
objcmd.executenonquery();
objcmd.commandtext = "insert into mytable (firstname, lastname)" +
" values (joe, thomas)";
objcmd.executenonquery();
// close the connection.
objconn.close();
}
} // end class
}// end namespace
注意:如果您没有将 office 安装到默认文件夹(c:\program files\microsoft office),请修改代码示例中的 m_strnorthwind 常数以匹配 northwind.mdb 的安装路径。 |
||||||||||||
| 8. | 将下面的代码添加到 form1.cs 中的 using 指令中:
using system.reflection; using system.runtime.interopservices; using excel = microsoft.office.interop.excel; |
||||||||||||
| 9. | 按 f5 生成并运行该示例。 |

