asp.net中如何批量导出access某表内容到word文档

所属分类: 网络编程 / ASP.NET 阅读数: 226
收藏 0 赞 0 分享

下面通过图文并茂的方式给大家介绍asp.net中批量导出access某表内容到word文档的方法,具体详情如下:

一、需求:

 需要将表中每一条记录中的某些内容导出在一个word文档中,并将这些文档保存在指定文件夹目录下

二、界面,简单设计如下:

三、添加office相关引用

添加后可在解决方案资源管理器中看到:

四、添加form1中的引用

using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using Microsoft.Office.Core;
using Word=Microsoft.Office.Interop.Word;
using System.Reflection;

五、窗体Form1中代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using Microsoft.Office.Core;
using Word=Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Threading;//线程需用,进程中
namespace word
{
 delegate void ShowProgressDelegate(int totalStep, int currentStep); //定义委托,异步调用
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }
  public string filepath = "D:\\zjy\\其他\\NCTDCBJYQ04.mdb"; //数据库所在位置设置
  public string path; //输出路径
  private void Form1_Load(object sender, EventArgs e)
  {
   string sqlstr = "select OBJECTID,CBFBM,CBFMC from CBF";
   //string sqlstr = "select * from CBF";
   DataSet ds = AccessDAO.getDataSetFromAccessTable(sqlstr, filepath);
   this.dataGridView1.DataSource = ds.Tables[0].DefaultView; 
   dataGridView1.AllowUserToAddRows = false;
  }
  private void textBox1_MouseClick(object sender, MouseEventArgs e)//输出路径设置
  {
   FolderBrowserDialog dilog = new FolderBrowserDialog();
   dilog.Description = "请选择文件夹";
   if (dilog.ShowDialog() == DialogResult.OK || dilog.ShowDialog() == DialogResult.Yes)
   {
    path = dilog.SelectedPath;
    this.textBox1.Text = path;
   }
  }
  object pathword;      //声明文件路径变量
  private void button2_Click(object sender, EventArgs e) //批量输出
  {
   ParameterizedThreadStart start = new ParameterizedThreadStart(SetProgress);
   Thread progressThread = new Thread(start);
   progressThread.IsBackground = true;//标记为后台进程,在窗口退出时,正常退出
   progressThread.Start();
  }
   /// <summary>
  /// 刷新进度条
  /// </summary>
  /// <param name="totalStep"></param>
  /// <param name="currentStep"></param>
  void ShowProgress(int totalStep, int currentStep)
  {
   this.progressBar1.Maximum = totalStep;
   this.progressBar1.Value = currentStep;
   if (this.progressBar1.Value * 100 / progressBar1.Maximum != 100)
   {
    this.label2.Text = "当前输出进度为:" + this.progressBar1.Value * 100 / progressBar1.Maximum + "%" + " 请耐心等待:)";
   }
   else if (this.progressBar1.Value * 100 / progressBar1.Maximum == 100)
   {
    this.label2.Text = "输出结束!";
   }
  }
  /// <summary>
  /// 设置当前进度
  /// </summary>
  /// <param name="state"></param>
  void SetProgress(object state)
  {
   if (this.textBox1.Text == "")
   {
    MessageBox.Show("请选择文件输出路径", "提示");
   }
   else
   {
    for (int i = 0; i < this.dataGridView1.Rows.Count; i++) //遍历获取table中需要的值,并分别创建word文档
    {
     #region 打开进度条
     Thread.Sleep(1);
     object[] objs = new object[] { this.dataGridView1.RowCount, i+1 };
     //异步调用
     this.Invoke(new ShowProgressDelegate(ShowProgress), objs);
     #endregion
     #region 获取word中需要添加的内容
     string dm = this.dataGridView1.Rows[i].Cells[1].Value.ToString();//承包方编码
     string mc = this.dataGridView1.Rows[i].Cells[2].Value.ToString();//承包方名称
     #endregion
     #region 创建word文档,并将内容写入word,并保存起来
     //初始化变量
     object Nothing = Missing.Value;      //COM调用时用于占位
     object format = Word.WdSaveFormat.wdFormatDocument; //Word文档的保存格式
     Word.ApplicationClass wordApp = new Word.ApplicationClass();    //声明一个wordAPP对象
     Word.Document worddoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);//新建一个word对象
     //向文档中写入内容
     string wordstr = "承包方代码:" + dm + "\n" + "承包方名称:" + mc;
     worddoc.Paragraphs.Last.Range.Text = wordstr;
     //保存文档   
     pathword = path + "\\" + dm; //设置文件保存路径
     worddoc.SaveAs(ref pathword, ref format, ref Nothing, ref Nothing,
      ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
      ref Nothing, ref Nothing, ref Nothing, ref Nothing,
      ref Nothing, ref Nothing, ref Nothing);
     //关闭文档
     worddoc.Close(ref Nothing, ref Nothing, ref Nothing); //关闭worddoc文档对象
     wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); //关闭wordApp组对象
     #endregion
    }
    MessageBox.Show("文档创建成功!","提示");
   }   
  }    
 }
}

六、读取数据库中表需要的数据库类AccessDAO.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Text.RegularExpressions; //正则表达式引用所需
namespace word
{
 //access的数据访问接口
 class AccessDAO
 {
  public static class Property
  {
   public static string accessFilePath = "d:\\nCTDCBJYQ04DataSet.mdb";
   //若放入主程序,则可如下设置
   //one mainFrm = (one)this.Owner;
   //string prjName = mainFrm.laPrj.Text;
   //string prjPath = mainFrm.laFile_Path.Text;
   // public static string accessFilePath = prjPath + "\\矢量数据\\" + prjName + ".mdb";
  }
  //从access数据库获取数据
  //dataFilePath指定access文件的路径
  //sql指定数据库的查询语句
  //DataSet为查询返回的数据集
  public static DataSet getDataSetFromAccessTable(string sql, string dataFilePath)
  {
   // 连接数据库 
   OleDbConnection connct = new OleDbConnection();
   string oleDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataFilePath;
   connct.ConnectionString = oleDB;
   //创建命令
   OleDbCommand command = new OleDbCommand(sql, connct);
   //打开数据库
   connct.Open();
   //执行命令
   DataSet dataSet = new DataSet();
   OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
   dataAdapter.Fill(dataSet);
   // 关闭连接 
   connct.Close();
   return dataSet;
  }
  //更新或者插入数据到access数据库
  //dataFilePath指定access文件的路径
  //sql指定数据库的更新或者插入语句
  //返回值int表示此次更新影响的行数
  public static int updateAccessTable(string sql, string dataFilePath)
  {
   // 连接数据库 
   OleDbConnection connct = new OleDbConnection();
   string oleDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataFilePath;
   connct.ConnectionString = oleDB;
   //打开数据库
   connct.Open();
   //执行命令
   OleDbCommand myCommand = new OleDbCommand(sql, connct);
   int res = myCommand.ExecuteNonQuery();
   // 关闭连接 
   connct.Close();
   return res;
  }
  //更新或者插入数据到access数据库
  //dataFilePath指定access文件的路径
  //command指定操作(更新或者插入)数据库的命令
  //返回值int表示此次更新影响的行数
  public static int updateAccessTable(OleDbCommand command, string dataFilePath)
  {
   // 连接数据库 
   OleDbConnection connct = new OleDbConnection();
   string oleDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataFilePath;
   connct.ConnectionString = oleDB;
   //打开数据库
   connct.Open();
   //执行命令
   //OleDbCommand myCommand = new OleDbCommand(sql, connct);
   command.Connection = connct;
   int res = command.ExecuteNonQuery();
   // 关闭连接 
   connct.Close();
   return res;
  }
  public bool ckDigital_Num(string digitalItem, int digitalNum)    //正则检查是否为数字,且位数一定
  {
   bool isDigital_Num = false;
   Regex reGen = new Regex(@"^\d{" + digitalNum.ToString("F0") + "}$");     //正则表达式,n位数字
   if (reGen.IsMatch(digitalItem))
    isDigital_Num = true;
   return isDigital_Num;
  }
 }
}

ok了,至此就可完成批量导出成word文档了

更多精彩内容其他人还在看

asp.net页面传值测试实例代码(前后台)

本文为大家详细介绍下asp.net页面传值的具体实现,感兴趣的朋友可以参考下哈,本人水平有限,还请各位朋友多多指教
收藏 0 赞 0 分享

ASP.NET中操作SQL数据库(连接字符串的配置及获取)

要想在ASP.NET中操作SQL数据库首先需要在WebConfig中配置数据库连接字符串,之后在.cs文件中获取连接字符串,具体的配置及获取方法如下,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

三层+存储过程实现分页示例代码

本文为大家介绍下三层+存储过程分页的具体实现,前后台及存储过程代码如下,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

DataGridView - DataGridViewCheckBoxCell的使用介绍

Datagridview是.net中最复杂的控件,Datagridview中,用户可以对行、列、单元格进行编程,下面与大家分享下DataGridViewCheckBoxCell的使用,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

asp.net中javascript的引用(直接引入和间接引入)

Asp.net 中引入Javascript的方法有很多,个人认为可以分为直接引入,和间接引入,下面是两种具体的引用方法,感兴趣的朋友可以参考下哈
收藏 0 赞 0 分享

Gridview用法大总结(全程图解珍藏版)

Gridview用法大总结啦!精彩效果截图加详细源代码注释,需要的朋友赶紧过来看看吧
收藏 0 赞 0 分享

HTTP错误500.19解决方法(定义了重复的节点)

HTTP 错误 500.19 - Internal Server Error 无法访问请求的页面,因为该页的相关配置数据无效
收藏 0 赞 0 分享

Asp.Net 无刷新文件上传并显示进度条的实现方法及思路

这篇文章详细介绍了无刷新文件上传并显示进度条的思路和代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Asp.net获取客户端IP常见代码存在的伪造IP问题探讨

如果某个网站是通过下面的代码获取IP,那么我们只要在Header里随意设置HTTP_VIA和X_FORWARDED_FOR,就可以达到伪造IP的目的
收藏 0 赞 0 分享

VS2010 水晶报表的使用方法

这篇文章简单介绍下VS2010 水晶报表的使用方法,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多