一、需求:

需要将表中每一条记录中的某些内容导出在一个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[].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 * / progressBar1.Maximum != )
{
this.label2.Text = "当前输出进度为:" + this.progressBar1.Value * / progressBar1.Maximum + "%" + " 请耐心等待:)";
}
else if (this.progressBar1.Value * / progressBar1.Maximum == )
{
this.label2.Text = "输出结束!";
}
} /// <summary>
/// 设置当前进度
/// </summary>
/// <param name="state"></param>
void SetProgress(object state)
{
if (this.textBox1.Text == "")
{
MessageBox.Show("请选择文件输出路径", "提示");
}
else
{
for (int i = ; i < this.dataGridView1.Rows.Count; i++) //遍历获取table中需要的值,并分别创建word文档
{
#region 打开进度条
Thread.Sleep();
object[] objs = new object[] { this.dataGridView1.RowCount, i+ };
//异步调用
this.Invoke(new ShowProgressDelegate(ShowProgress), objs);
#endregion #region 获取word中需要添加的内容
string dm = this.dataGridView1.Rows[i].Cells[].Value.ToString();//承包方编码
string mc = this.dataGridView1.Rows[i].Cells[].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文档了

批量导出access某表内容到word文档的更多相关文章

  1. Java 导出数据库表信息生成Word文档

    一.前言 最近看见朋友写了一个导出数据库生成word文档的业务,感觉很有意思,研究了一下,这里也拿出来与大家分享一波~ 先来看看生成的word文档效果吧 下面我们也来一起简单的实现吧 二.Java 导 ...

  2. C#导出文本内容到word文档源码

    将做工程过程中较好的代码片段珍藏起来,下面的代码内容是关于C#导出文本内容到word文档的代码,希望能对小伙伴们也有好处.<%@ Page Language="C#" Aut ...

  3. 用注册表清除Office Word文档杀手病毒

    不久前,笔者打开word文件时遇到了一件离奇的怪事,常用的Word文件怎么也打不开,总是出现提示框:"版本冲突:无法打开高版本的word文档".再仔细查看,文件夹里竟然有两个名字一 ...

  4. java通过freemarker导出包含富文本图片的word文档

    废话不多说,进入正题! 本文重点在于:对富文本图片的导出(基础的freemarker+word模板导出这里不做详细解说哈) 参考文章:http://www.cnblogs.com/liaofeifig ...

  5. 孤荷凌寒自学python第七十九天开始写Python的第一个爬虫9并使用pydocx模块将结果写入word文档

    孤荷凌寒自学python第七十九天开始写Python的第一个爬虫9 (完整学习过程屏幕记录视频地址在文末) 今天在上一天的基础上继续完成对我的第一个代码程序的书写. 到今天终于完成了对docx模块针对 ...

  6. Java生成word文档

    itext-rtf-2.1.7.jar,下载地址:http://download.csdn.net/detail/xuxu198899223/7717727 itext-2.1.7.jar 下载地址: ...

  7. c#word文档输出

    在工作中有时需要把内容用word文档展示出来 在写代码前要引用word的dll Microsoft.Office.Interop.Word“ sing System; using System.Col ...

  8. C# 导出word文档及批量导出word文档(4)

          接下来是批量导出word文档和批量打印word文件,批量导出word文档和批量打印word文件的思路差不多,只是批量打印不用打包压缩文件,而是把所有文件合成一个word,然后通过js来调用 ...

  9. C# 导出word文档及批量导出word文档(3)

    在初始化WordHelper时,要获取模板的相对路径.获取文档的相对路径多个地方要用到,比如批量导出时要先保存文件到指定路径下,再压缩打包下载,所以专门写了个关于获取文档的相对路径的类. #regio ...

随机推荐

  1. 全新 Mac 安装指南(编程篇)(环境变量、Shell 终端、SSH 远程连接)

    注:本文专门用于指导对计算机编程与设计(尤其是互联网产品开发与设计)感兴趣的 Mac 新用户,如何在 Mac OS X 系统上配置开发与上网环境,另有<全新 Mac 安装指南(通用篇)>作 ...

  2. 剑指Offer面试题:35.将字符串转换为数字

    一.题目:将字符串转换为数字 题目:写一个函数StrToInt,实现把字符串转换成整数这个功能.当然,不能使用atoi或者其他类似的库函数. 二.代码实现 (1)考虑输入的字符串是否是NULL.空字符 ...

  3. [译]Kinect for Windows SDK开发入门(十八):Kinect Interaction交互控件

    本文译自 http://dotneteers.net/blogs/vbandi/archive/2013/03/25/kinect-interactions-with-wpf-part-i-getti ...

  4. Android什么时候进行View中Background的加载

    对大多数Android的开发者来说,最经常的操作莫过于对界面进行布局,View中背景图片的加载是最经常做的.但是我们很少关注这个过程,这篇文章主要解析view中背景图片加载的流程.了解view中背景图 ...

  5. 如何创建一个AJAX-Enabled WCF Service

      原创地址:http://www.cnblogs.com/jfzhu/p/4041638.html 转载请注明出处   前面的文章中介绍过<Step by Step 创建一个WCF Servi ...

  6. Oozie分布式任务的工作流——脚本篇

    继前一篇大体上翻译了Email的Action配置,本篇继续看一下Shell的相关配置. Shell Action Shell Action可以执行Shell脚本命令,工作流会等到shell完全执行完毕 ...

  7. Atitti  onvif 设备发现与原理

    Atitti  onvif 设备发现与原理 1.1. ,有以下几个步骤:1 1.2. 设备搜索原理及编程技巧:2 1.3. Ws disconvert 的组播地址和端口就是37022 1)发现ipca ...

  8. OpenGL Shader in OpenCASCADE

    OpenGL Shader in OpenCASCADE eryar@163.com Abstract. As implementation of one of the strategic steps ...

  9. Matlab 循环读入和输出

    这两天要给导师做实验,因此要写Matlab程序,在做程序的时候,涉及到了循环读入和输出,查找相关资料 代码如下 : Image=['F:\\SYTP\\',num2str(i),'.jpg']; Te ...

  10. Android图片处理

    相信做Android开发的小伙伴对于Android图片压缩.裁剪一定有很深的印象,今天我将带领大家一起学习一下这个看着高深莫测的知识,以便再以后的学习.工作中可以帮助到大家. 首先我们看一下这个问题出 ...