c#如何将html标签写入指定的excel中

如题所述

  有这样的任务,通过ADO.NET从数据库读取数据到DataSet,数据绑定到DataGrid或者.NET2.0里的新控件DataGridView,最后将数据写入Excel文件,提供给用户进一步的分析,如打印、图表等。
  有这样的任务,通过ADO.NET从数据库读取数据到DataSet,数据绑定到DataGrid或者.NET2.0里的新控件DataGridView,最后将数据写入Excel文件,提供给用户进一步的分析,如打印、图表等。
  前面的步骤都很简单,关键是写Excel,毕竟Excel不是数据格式,在C#中调用Excel表格要使用到Excel的COM组件。如果你装的Office2000 ,在"C:\Program Files\Microsoft Office\Office"可以找到这个COM组件"EXCEL9.OLB",这些COM组件都是非受管代码的,要在C#中使用这些非受管代码的COM组件,就必须把他们转换成受管代码的类库。所以在用C#调用Excel表格之前,必须完成从COM组件的非受管代码到受管代码的类库的转换。在DOS命令行下键入:
  tlbimp excel9.olb
  这样在excel9.olb目录下就产生了三个DLL文件:"Excel.dll"、"Office.dll"、"VBIDE.dll"。
  但Office2000以后的版本没有*.olb文件,对2003可以直接到OFFICE安装目录,利用.net 中带的工具在命令提示符下执行:
  tlbimp excel.exe
  还是会生成Excel.dll,在工程中引用这个文件就可以了。
  这样与Excel有关的类都加了进来,别忘了在namespace里添加using Excel。
  窗体上添加一个按钮,对Click事件方法如下:
  private void button1_Click(object sender, EventArgs e)
  {
  int count = this.archiverdbDataSet.channel.Rows.Count;//获取数据表中DataRow行总数
  int column = this.archiverdbDataSet.channel.Columns.Count;//获取数据表中列总数
  Excel.ApplicationClass excelapp = new ApplicationClass();
  //Make Excel Application Visible
  excelapp.Visible = true;
  //写入特定文件
  //Excel.Workbook wb = excelapp.Workbooks.Open(string filename,
  // Type.Missing,Type.Missing,Type.Missing,Type.Missing,
  // Type.Missing,Type.Missing,Type.Missing,Type.Missing,
  // Type.Missing,Type.Missing,Type.Missing,Type.Missing,
  // Type.Missing,Type.Missing);
  Excel.Workbook wb = excelapp.Application.Workbooks.Add(true);
  for (int x = 1; x <= count; x++)
  {
  for (int y = 1; y <= column; y++)
  {
  excelapp.Cells[x, y] = this.archiverdbDataSet.channel.Rows[x- 1].ItemArray[y - 1];
  }
  }
  string tname = "C:\Book2.xls";
  wb.SaveAs(tname, Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value,Missing.Value, Missing.Value, Missing.Value);
  try
  {
  wb.Saved = true;
  excelapp.UserControl = false;
  //excelapp.Quit();
  }
  catch(System.Exception op)
  {
  MessageBox.Show("wrong" + op.Message);
  }
  }
  以上在VS.net 2005里测试通过。当然你还可以把Excel做的漂亮点,参考文档有例子,不过没试过。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-01
这个就要用到配置文件来做,其实没必要那样做更麻烦的。
第2个回答  2014-11-01
c# 写excel 实例可以提供
相似回答