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

所属分类: 网络编程 / ASP.NET 阅读数: 224
收藏 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文档了

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

运行page页面时的事件执行顺序及页面的回发与否深度了解

page页面时的事件执行顺序的了解对于一些.net开发者起到者尤关重要的作用;页面的回发与否会涉及到某些事件执行与不执行,在本文中会详细介绍,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

Web.config(应用程序的配置信息)总结

Web.config文件是一个XML文本文件,它用来储存 ASP.NET Web 应用程序的配置信息(如最常用的设置ASP.NET Web 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中,接下来详细介绍一下配置情况,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

C#时间格式化(Datetime)用法详解

C#时间格式化Datetime.ToString参数format格式详细用法,本文将进行介绍,感兴趣的朋友可以了解下啊
收藏 0 赞 0 分享

实现onmouseover和onmouseout应用于RadioButtonList或CheckBoxList控件上

一直想实现onmouseover和onmouseout应用于RadioButtonList或CheckBoxList控件上。此功能就是当鼠标经过时RadioButtonList或CheckBoxList每一个Item时,让Item有特效显示,离开时,恢复原样有演示动画,感兴趣的朋
收藏 0 赞 0 分享

Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习

关于图片盗链这个问题,毕竟是自己的劳动成功,很多人不希望别人就那么轻易地偷走了;反盗链的程序其实很简单,熟悉ASP.NET 应用程序生命周期的话很容易就可以写一个,运用HttpModule在BeginRequest事件中拦截请求就ok了
收藏 0 赞 0 分享

asp.net Grid 导出Excel实现程序代码

看了FineUI中的将Grid导出为Excel的实现方法,实际上是可以非常简单。看来很难的问题,变换一种思路就可以非常简单
收藏 0 赞 0 分享

使用C#处理WebBrowser控件在不同域名中的跨域问题

我们在做web测试时,经常会使用WebBrowser来进行一些自动化的任务而有些网页上面会用IFrame去嵌套别的页面,这些页面可能不是在相同域名下的,这时就会出现跨域问题,无法直接在WebBrowser中获取到IFrame中的元素,接下来介绍如何解决此问题,需要了解的朋友可以参
收藏 0 赞 0 分享

.NET 下运用策略模式(组合行为和实体的一种模式)

我简单的理解策略模式就是把行为(方法)单独的抽象出来,并采用组合(Has-a)的方式,来组合行为和实体的一种模式比如,.NET中对数组排序的Sort的方法就是一个策略模式的实现模板
收藏 0 赞 0 分享

使用Entity Framework(4.3.1版本)遇到的问题整理

在这里记录一下之前使用Entity Framework(4.3.1版本)遇到的问题:更新没有设置主键的表、更改Code-First的默认连接、检测字符串截断错误,需要的朋友可以参考下
收藏 0 赞 0 分享

Asp.net利用JQuery AJAX实现无刷新评论思路与代码

Asp.net利用JQuery AJAX实现无刷新评论,此功能是每一个从事asp.net开发者的朋友都希望实现的,本文利用闲暇时间整理了一些,有需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多