C # export Word table code

Source: Internet
Author: User

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.UI;using System.web.ui.webcontrols;using system.reflection;using system.io;using system.data.sqlclient;using System.Data; Namespace webapplication1{    Public partial class printword:system.web.ui.page    {    &N Bsp   protected void Page_Load (object sender, EventArgs e)         {           /Querydataset ();       }       //<summary>       //export        //</summary>       //<param name= "Sender" >& lt;/param>       //<param name= "E" ></param>        protected VO ID Btnprint_click (object sender, EventArgs e)         {            Print ( );       }      /<summary>       ///export word        ///build Word Solution &nbs P      ///1. First introduce the template        ///2. Determine if the row is the same as the query dataset, and if it is smaller than the dataset, it will be added to the number of rows        / 3. Get the table and assign values for each cell        ///4. Set the color change of the cell according to different conditions        //</summary>& nbsp       private void Print ()         {           //first introduced word& nbsp           Microsoft.Office.Interop.Word.Application app; Application             Microsoft.Office.Interop.Word.Document Doc;  //Create a document             String templatefile = ""; Declare the template name to use             String FileName = ""; The path name of the new file             String Fname = ""; New file name             app = Microsoft.Office.Interop.Word.AppLication ();//Create Instance app             doc = new Microsoft.Office.Interop.Word.Document ();  //creating an Instance document             templatefile = Server.MapPath ("~/test/ Half month with forecast-Changan automobile Daily Express 2015010x.dot "); Server.MapPath ("~/test/caxsmb.dot");//Find template             Fname = DateTime.Now.ToString (" Test the same document name try ") +". Doc ";//create a new file name yyyymmddhhmmss            FileName = Server.MapPath (" ~/tes t/download/"+ Fname);//The path of the new file            //decide to have the same document will be deleted           & nbsp if (file.exists (FileName))             {              &NBS P File.delete (FileName);           }            File.Copy (Templ Atefile, FileName);//copy template to new file            //Set properties for new file           &NBSP ; Object obj_filename = Filename;            Object Visible = false;            Object Rea DOnly = false;            Object missing = system.reflection.missing.value;    &NB Sp      //Create new document             doc = app. Documents.Open (            ref obj_filename, ref missing, ref ReadOnly, ref missing,  & nbsp         ref missing, ref missing, ref missing, ref missing,            R EF missing, ref missing, ref missing, ref visible,            ref missing, ref missing, ref missing,            ref missing);           //Add form   &NBS P        //dataset ds = GetDataSet ();//Get Program collection            //int Dscount = Ds. Tables[0]. rows.count;//getting data from a database table     &NBSp      //int Doccount = doc. TABLES[1]. Rows.Count; Get data for tables in documents            //if (Dscount > Doccount)//create rows when actual data is about tabular data            //{           //   //start adding lines         &NBS P  //   microsoft.office.interop.word.table newtable = doc. tables[1];           //   for (int row = 0; row < Dscount-doccount; row++) & nbsp          //   {           //      &NBS P;object BeforeRow = doc. TABLES[1]. rows[doccount-1];           //       doc. TABLES[1]. Rows.Add (ref BeforeRow); Line add to table            //   }           //}  & nbsp         Doc. Activate ();                   //Match form datasets                  &N Bsp     Microsoft.Office.Interop.Word.Document odoc = GetDocument (FileName);//Get new documents             DataSet ds = GetDataSet ();//Get Program collection            //Start judging there are several tables/because there are three sheets in the template   & nbsp         for (int tablepos = 1; tablepos <= odoc. Tables.count; tablepos++)             {               //All in a single table &NB Sp               if (Tablepos = = 1)                 {                    int dscount = ds. Tables[0]. rows.count;//get data from database tables                     int doccount = odoc. TABLES[1]. Rows.Count; Get data for tables in documents             &NBSP;       if (Dscount > Doccount)//When actual data is about tabular data, create line                     {                       //start adding lines     & nbsp                   Microsoft.Office.Interop.Word.Table newtable = doc. tables[1];                        for (int row = 0; row < ( Dscount-doccount) +1; row++)                         {        &NB Sp                   Object beforerow = newtable.rows[doccount];    &N Bsp                       NEWTABLE.ROWS.ADD (ref beforerow); Line add to table                        }        &nBsp          }                   //After the form is completed, add data to Cell assignment                     for (int rcount = 0; Rcount < ds. Tables[0]. Rows.Count; rcount++)                     {                        for (int ccount = 0; ccount < ds. Tables[0]. Columns.count; ccount++)                         {                           //doc. TABLES[1]. Rows[rowpos]. Cells[columpos]. range.text                            StrText. = ds. Tables[0]. Rows[rcount][ccount]. ToString ();                            Doc. Tables[1]. ROWS[RCOUNT+2]. Cells[ccount + 1]. Range.Text = strtext;//starting from the second line                             if (StrText = = "R")                           &NBSP ; {                                Doc. TABLES[1]. ROWS[RCOUNT+2]. Cells[ccount + 1]. Range.Shading.BackgroundPatternColor = microsoft.office.interop.word.wdcolor.wdcolorlightblue;                           }            &N Bsp          }                   }    & nbsp          }           }           / /close process             Object issave = TRue;            Doc. Close (ref issave, ref missing, ref missing);            app. Quit (ref issave, ref missing, ref missing);            //close Word process             String url = "~/test/download /"+ Fname;;            Response.Redirect (URL);            Sy Stem. Runtime.InteropServices.Marshal.ReleaseComObject (APP);    //free memory space         }       //<summary>    &NBSP ;  ///query data set        //</summary>       //<returns></return s>        public DataSet GetDataSet ()         {        &NBSP ;   string sConnectionString = "server=.; Uid=sa;pwd=123456;database=xiaoshoudb ";            SqlConnection OBJCOnn = new SqlConnection (sConnectionString);            objConn.Open ();      & nbsp     SqlDataAdapter da = new SqlDataAdapter ("select * from  yuexiaoshou", objconn);      &NBS P     DataSet ds = new DataSet ();            da. Fill (DS);            objconn.close ();            return DS;&NB Sp      }       //<summary>       ///To get the properties under this file from the file address        //</summary>       //<param name= "Fileroad" ></param>& nbsp      //<returns></returns>        Public Microsoft.Office.Interop.Word.Document getdocument (String fileroad)         {      & nbsp     Microsoft.Office.Interop.Word.Application app;    &nbsp       app = new Microsoft.Office.Interop.Word.Application ();            OBJEC T ofilename = fileroad;  //server.mappath (fileroad);//depending on the path of Word        //("~/test/test read/write. docx");  //@ "f:\ database. docx";            Object oreadonly = false;        &NB Sp   Object omissing = system.reflection.missing.value;            Microsoft.office.interop.word._application oword;            Microsoft.Office.Interop.Word.Document odoc;            oword = new Microsoft.Office.Interop.Word.Application ();            oword.visible = false;            odoc = OWord.Documents.Open (ref ofilename, ref omissing, ref oreadonly, ref omissing, R EF omissing,            ref omissing, ref omissing, ref omissing, refomissing, ref omissing, ref omissing, ref omissing);            return odoc;    &N Bsp  }   }}

C # Export Word table code

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.