How to bulk export the contents of an Access table to a Word document in asp.net practical tips

Source: Internet
Author: User
Tags ole reflection static class access database

The following is an illustrated way to introduce you to the method of asp.net in bulk export of Access table contents to Word documents, as detailed below:

First, the demand:

You need to export some content from each record in a table to a Word document and save the documents in a specified folder directory

Second, the interface, simple design as follows:

Iii. adding office-related references

After you add it, you can see it in Solution Explorer:

Iv. add a reference in 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;

The code in the form Form1 is as follows:

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; The using system.threading;//thread is required to namespace Word {delegate void showprogressdelegate (int totalstep, int currentstep) in the process;
  Defines a delegate that asynchronously invokes the public partial class Form1:form {public Form1 () {InitializeComponent (); public string filepath = "d:\\zjy\\ other \\NCTDCBJYQ04.mdb"; Set public string path where the database is located; Output 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)//output path setting {FolderBrowserDialog Dilog = new Folde
   Rbrowserdialog (); Dilog.
   Description = "Please select folder"; if (Dilog. ShowDialog () = = DialogResult.OK | | Dilog. ShowDialog () = = Dialogresult.yes) {path = Dilog.
    SelectedPath;
   This.textBox1.Text = path;      } object Pathword; Declaring file path variable private void button2_click (object sender, EventArgs e)//bulk Output {parameterizedthreadstart start = new Par
   Ameterizedthreadstart (setprogress);
   Thread progressthread = new Thread (start);
  Progressthread.isbackground = true;//marked as background process, when the window exits, the normal exit Progressthread.start (); ///<summary>///Refresh progress bar///</summary>///<param name= "Totalstep" ></param>///<p Aram Name= "Currentstep" ></param> void showprogress (int totalstep, int currentstep) {This.progressBar1.Max
   Imum = Totalstep;
   This.progressBar1.Value = Currentstep; if (this.progressBar1.Value * 100/progressbar1.maximum!=) {this.label2.Text = "Current output progress is:" + this.progressBar1.Value * 100/progressbar
   1.Maximum + "%" + "Please wait patiently:";
   else if (this.progressBar1.Value * 100/progressbar1.maximum = =) {This.label2.Text = "End of output!"; }///<summary>///set Current progress///</summary>///<param name= "state" ></param> void SETP
   Rogress (object state) {if (This.textBox1.Text = = "") {MessageBox.Show ("Please select File output path", "prompt"); else {for (int i = 0; i < this.dataGridView1.Rows.Count i++)//traversal Gets the value needed in the table and creates the Word document {#reg
     Ion Open progress bar thread.sleep (1);
     object[] Objs = new object[] {this.dataGridView1.RowCount, i+1}; Call this asynchronously.
     Invoke (New ShowProgressDelegate (showprogress), OBJS); #endregion #region Get what you want to add in Word string dm = This.datagridview1.rows[i]. CELLS[1]. Value.tostring ()//Contractor code String MC = This.datagridview1.rows[i]. CELLS[2]. Value.tostring ()//contractor name
     #endregion #region Create a Word document and write the content to Word and save it//Initialize the variable object nothing = Missing.Value; COM invocation for placeholder object format = Word.WdSaveFormat.wdFormatDocument;    Save format for Word documents Word.applicationclass WordApp = new Word.applicationclass (); Declares a WordApp object word.document WordDoc = WORDAPP.DOCUMENTS.ADD (ref nothing, ref none, ref nothing, ref nothing);//New
     Build a Word object//write content to the document string wordstr = "Contractor code:" + DM + "\ n" + "Contractor Name:" + MC; WordDoc.
     Paragraphs.Last.Range.Text = Wordstr; Save Document Pathword = path + "\" + DM; Set file save path WordDoc. SaveAs (ref pathword, ref format, ref nothing, ref nothing, ref no, ref nothing, ref no, ref nothing, ref N
     Othing, ref nothing, ref no, ref nothing, ref no, ref nothing, ref no, ref nothing); Closes the document WordDoc. Close (ref nothing, ref no, ref nothing); Closes the WordDoc Document Object Wordapp.quit (ref nothing, ref no, ref nothing); Closes the WordApp group object #endrEgion} MessageBox.Show ("Document creation successful!", "prompt"); }   
  }    
 }
}

six, the database class AccessDAO.cs code required to read the tables in the database is as follows:

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; The regular expression refers to the data provider class Accessdao {public static class Property {public static stri that is required namespace Word {//access
   ng Accessfilepath = "D:\\nctdcbjyq04dataset.mdb"; If you put it in the main program, you can set//one mainfrm = (one) as follows.
   Owner;
   string prjname = MainFrm.laPrj.Text;
   string prjpath = MainFrm.laFile_Path.Text;
  public static string Accessfilepath = Prjpath + "\ Vector data \" + Prjname + ". mdb"; ///Get data from Access database//datafilepath Specifies the path to the Access file//sql the query statement for the specified database//dataset the dataset that is returned for the query public static dataset Getdatas
   Etfromaccesstable (String sql, String DataFilePath) {//connection database OleDbConnection connct = new OleDbConnection ();
   string OLE DB = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + datafilepath; Connct.
   ConnectionString = OLE DB; Creating commands OleDbCommand Command = new OleDbCommand (SQL, connct); Open the database connct.
   Open ();
   Execute command DataSet = new DataSet ();
   OleDbDataAdapter dataAdapter = new OleDbDataAdapter (command);
   DataAdapter.Fill (DataSet); Closes the connection connct.
   Close ();
  return dataSet; //update or insert data into an Access database//datafilepath specify the path to the Access file//sql the update of the specified database or the INSERT statement//return value int represents the number of rows that this update affects public static int upd
   Ateaccesstable (String sql, String DataFilePath) {//connection database OleDbConnection connct = new OleDbConnection ();
   string OLE DB = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + datafilepath; Connct.
   ConnectionString = OLE DB; Open the database connct.
   Open ();
   Execute command OleDbCommand mycommand = new OleDbCommand (sql, connct);
   int res = Mycommand.executenonquery (); Closes the connection connct.
   Close ();
  return res;  //update or insert data into an Access database//datafilepath specify the path to the Access file//command the command//return value of the specified action (update or INSERT) database represents the number of rows that this update affects public static 
 int updateaccesstable (OleDbCommand command, string datafilepath) {//Connection database  OleDbConnection connct = new OleDbConnection ();
   string OLE DB = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + datafilepath; Connct.
   ConnectionString = OLE DB; Open the database connct.
   Open ();
   Execute command//oledbcommand mycommand = new OleDbCommand (sql, connct); Command.
   Connection = connct; int res = command.
   ExecuteNonQuery (); Closes the connection connct.
   Close ();
  return res;
   public bool Ckdigital_num (string digitalitem, int digitalnum)//Regular check is a number, and the number of digits must be {bool Isdigital_num = false;     Regex regen = new Regex (@ "^\d{" + digitalnum.tostring ("F0") + "}$");
   Regular expressions, n-digit if (Regen.ismatch (digitalitem)) Isdigital_num = true;
  return isdigital_num; }
 }
}

OK, so you can complete the bulk export to a Word document

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.