精华内容
下载资源
问答
  • c# 生成word

    2018-03-22 21:41:11
    使用C#生成word文件的代码示例【包含生成wold所必须的两个类库】
  • C#生成Word

    2018-03-13 17:12:01
    打开Form1源代码,有使用示例,可插入文字,图片,表格,设置字体,颜色,居中等,都封装到了WordHelper类中,注意:需要安装Office,因为调用Com组件,别没装office就在评论里说不能用报错之类的。
  • C#生成word

    2012-07-09 14:03:12
    先在WORD文档中插入书签,然后用C#生成相应的书签的值,详情请查阅代码,内有说明,本版本为VS2010
  • 主要介绍了C#生成word记录实例解析,很实用的功能,需要的朋友可以参考下
  • 主要介绍了C#生成Word文档代码示例,本文直接给出代码实例,需要的朋友可以参考下
  • C#生成word文档

    2013-07-17 11:33:08
    C#生成word文档,在线编辑word,内涵代码
  • C#生成Word文档

    2020-06-16 16:57:25
    该demo使用c#实现word文档的生成,网上大部分生成word文档都需要引用com组件,该demo不需要引用com组件
  • 主要为大家详细介绍了C#生成Word文件,包括图片、文字等素材,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • c#生成WORD

    千次阅读 2009-10-16 17:21:00
    原文出处http://blog.163.com/fengqingch/blog/static/21567772008019101230429/ 首先引入类库,Microsoft.Office.Interop.Word,然后进行编程。代码如下: using System; using System.Collections.Generic; using ...

    原文出处http://blog.163.com/fengqingch/blog/static/21567772008019101230429/

     

    首先引入类库,Microsoft.Office.Interop.Word,然后进行编程。代码如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.Office.Interop.Word;

    namespace WordTest
    {
    public partial class Form1 : Form
    {
    object strFileName;
    Object Nothing;
    Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    Document myWordDoc;
    string strContent = "";

    public Form1()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    createWord();
    //openWord();
    }

    private void createWord()
    {
    strFileName = System.Windows.Forms.Application.StartupPath + "test.doc";
    if (System.IO.File.Exists((string)strFileName))
    System.IO.File.Delete((string)strFileName);
    Object Nothing = System.Reflection.Missing.Value;
    myWordDoc = myWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

    #region 将数据库中读取得数据写入到word文件中

    strContent = "你好nnr";
    myWordDoc.Paragraphs.Last.Range.Text = strContent;

    strContent = "这是测试程序";
    myWordDoc.Paragraphs.Last.Range.Text = strContent;


    #endregion

    //将WordDoc文档对象的内容保存为DOC文档
    myWordDoc.SaveAs(ref strFileName, 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, ref Nothing);
    //关闭WordDoc文档对象
    myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
    //关闭WordApp组件对象
    myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

    this.richTextBox1.Text = strFileName + "rn" + "创建成功";

    }
    private void openWord()
    {
    fontDialog1.ShowDialog();
    System.Drawing.Font font = fontDialog1.Font;
    object filepath = "D:asp.docx";
    object oMissing = System.Reflection.Missing.Value;
    myWordDoc = myWordApp.Documents.Open(ref filepath, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    myWordDoc.Content.Font.Size = font.Size;
    myWordDoc.Content.Font.Name = font.Name;
    myWordDoc.Save();
    richTextBox1.Text = myWordDoc.Content.Text;


    myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
    myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
    }

    }
    ======================================
    另外当然还需要引用Interop.Word.Dll.

      代码如下:

    ///#region 打开Word文档,并且返回对象wDoc,wDoc
    ///
    /// 打开Word文档,并且返回对象wDoc,wDoc
    ///
    /// 完整Word文件路径+名称
    /// 返回的Word.Document wDoc对象
    /// 返回的Word.Application对象
    public static void CreateWordDocument(string FileName,ref Word.Document wDoc,ref Word.Application WApp)
    {
    if(FileName == "") return;
    Word.Document thisDocument = null;
    Word.FormFields formFields = null;
    Word.Application thisApplication = new Word.ApplicationClass();
    thisApplication.Visible = true;
    thisApplication.Caption = "";
    thisApplication.Options.CheckSpellingAsYouType = false;
    thisApplication.Options.CheckGrammarAsYouType = false;

    Object filename = FileName;
    Object ConfirmConversions = false;
    Object ReadOnly = true;
    Object AddToRecentFiles = false;

    Object PasswordDocument = System.Type.Missing;
    Object PasswordTemplate = System.Type.Missing;
    Object Revert = System.Type.Missing;
    Object WritePasswordDocument = System.Type.Missing;
    Object WritePasswordTemplate = System.Type.Missing;
    Object Format = System.Type.Missing;
    Object Encoding = System.Type.Missing;
    Object Visible = System.Type.Missing;
    Object OpenAndRepair = System.Type.Missing;
    Object DocumentDirection = System.Type.Missing;
    Object NoEncodingDialog = System.Type.Missing;
    Object XMLTransform = System.Type.Missing;

    try
    {
    Word.Document wordDoc =
    thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
    ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
    ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
    ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
    ref NoEncodingDialog, ref XMLTransform );

    thisDocument = wordDoc;
    wDoc = wordDoc;
    WApp = thisApplication;
    formFields = wordDoc.FormFields;
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

    }
    #endregion

    调用上面静态方法,打开目标文件并且把DataGrid中数据填充到对应Word标签中去

    ///#region Word填充数据(For Example)
    ///
    /// Word填充数据
    ///
    private void WordLoadData()
    {
    Word.Document wDoc=null;
    Word.Application wApp=null;
    sysFun.CreateWordDocument("E://监测报告(new).dot",ref wDoc,ref wApp);

    //对标签"C"进行填充
    object bkmC="C";
    if(wApp.ActiveDocument.Bookmarks.Exists("C") == true)
    {
    wApp.ActiveDocument.Bookmarks.get_Item
    (ref bkmC).Select();
    }
    wApp.Selection.TypeText(this.txt1.Text);
    object bkmG = "TWaterTable3";
    object unit;
    object count; //移动数
    object extend;


    extend = Word.WdMovementType.wdExtend;
    unit = Word.WdUnits.wdCell;
    //把DataGrid中数据填充到标签TWaterTable3上
    if(wApp.ActiveDocument.Bookmarks.Exists("TWaterTable3") == true)
    {
    wApp.ActiveDocument.Bookmarks.get_Item
    (ref bkmG).Select();

    for(int i=0;i {
    if(i==0)
    {
    count=1;
    }
    else
    {
    count=0;
    }
    //需填充5列数据
    wApp.Selection.Move(ref unit,ref count);
    wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[0].Text);
    count=1;

    wApp.Selection.Move(ref unit,ref count);
    wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[1].Text);

    wApp.Selection.Move(ref unit,ref count);
    wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[2].Text);

    wApp.Selection.Move(ref unit,ref count);
    wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[3].Text);

    wApp.Selection.Move(ref unit,ref count);
    wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[4].Text);
    //换行
    wApp.Selection.MoveRight(ref unit,ref count,ref extend);
    }
    }
    }
    #endregion


      然后就OK了,在对标签表控制要注意列循环和换行.


    C# 操作Excel(导入导出)


      有很多朋友说需要C# 导出到Excel的代码,现共享给大家


    ///
    /// 读取Excel文档
    ///
    /// 文件名称
    /// 返回一个数据集
    public DataSet ExcelToDS(string Path)
    {
    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    conn.Open();
    string strExcel = "";
    OleDbDataAdapter myCommand = null;
    DataSet ds = null;
    strExcel="select * from [sheet1$]";
    myCommand = new OleDbDataAdapter(strExcel, strConn);
    ds = new DataSet();
    myCommand.Fill(ds,"table1");
    return ds;
    }


    ///
    /// 写入Excel文档
    ///
    /// 文件名称
    public bool S***eFP2toExcel(string Path)
    {
    try
    {
    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    conn.Open();
    System.Data.OleDb.OleDbCommand cmd=new OleDbCommand ();
    cmd.Connection =conn;
    //cmd.CommandText ="Update [sheet1$] SET 姓名='2005-01-01' Where 工号='日期'";
    //cmd.ExecuteNonQuery ();
    for(int i=0;i {
    if(fp2.Sheets [0].Cells[i,0].Text!="")
    {
    cmd.CommandText ="Insert INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+
    fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+
    "','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')";
    cmd.ExecuteNonQuery ();
    }
    }
    conn.Close ();
    return true;
    }
    catch(System.Data.OleDb.OleDbException ex)
    {
    System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message );
    }
    return false;
    }


      这种方法是相当有效的。


      下附:VB.NET版实现word打开与关闭,有兴趣的朋友可以研究一下

    VB.NET实现word打开与关闭


    Imports Word

    '打开

    Dim mWordapp As Word.Application 'word 应用程序

    Dim mobjDoc As Word.Document 'word 文档

    Dim fullFileName as string '文件路径

    mWordapp = CreateObject("Word.Application")

    mobjDoc = mWordapp.Documents.Add(FullFileName)

    '关闭

    Dim missing As Object = System.Reflection.Missing.Value

    mWordapp.Application.Quit()

    If Not mobjDoc Is Nothing Then

    '垃圾回收

    System.Runtime.InteropServices.Marshal.ReleaseComObject(mobjDoc)

    mobjDoc = Nothing

    End If

    If Not mWordapp Is Nothing Then

    System.Runtime.InteropServices.Marshal.ReleaseComObject(mWordapp)

    mWordapp = Nothing

    End If

    '真正释放word进程

    GC.Collect()

     

     

     

     

    在web应用程序中,我们是不是很发愁打印问题,您是不是有过为了打印写Activex的经历,我们有没有想过,Word和Excel的打印功能能被我们 利用起来呢?只要我们将我们将数据导出到Excel或者Word中,打印岂不是小case了么。下面就谈谈如何让GridView自己支持导出Excel 和Word 。
        首先增加了两个属性,用于指示是否支持Excel导出和Word导出

       // 增加了一个设置是否显示“导出Word”按钮的属性
             /**/ ///   <summary>
            
    ///  排序提示信息
            
    ///   </summary>
            [
            Description(
    " 显示导出到Word " ),
            Category(
    " 扩展 " ),
             DefaultValue(
    true )
            ]
            
    public   virtual   bool  ShowExportWord
            
    {
                
    get
                
    {
                    
    object  obj2  =   this .ViewState[ " ShowExportWord " ];
                    
    if  (obj2  !=   null )
                    
    {
                        
    return  ( bool )obj2;
                    }

                    
    return   true ;
                }

                
    set
                
    {
                    
    bool  aShowExportWord  =   this .ShowExportWord;
                    
    if  (value  !=  aShowExportWord)
                    
    {
                        
    this .ViewState[ " ShowExportWord " =  value;
                        
    if  ( base .Initialized)
                        
    {
                            
    base .RequiresDataBinding  =   true ;
                        }

                    }

                }

            }

            
    // 增加了一个设置是否显示“导出Excel”按钮的属性
            [
           Description(
    " 显示导出到Excel " ),
           Category(
    " 扩展 " ),
           DefaultValue(
    true )
           ]
            
    public   virtual   bool  ShowExportExcel
            
    {
                
    get
                
    {
                    
    object  obj2  =   this .ViewState[ " ShowExportExcel " ];
                    
    if  (obj2  !=   null )
                    
    {
                        
    return  ( bool )obj2;
                    }

                    
    return   true ;
                }

                
    set
                
    {
                    
    bool  aShowExportExcel  =   this .ShowExportExcel;
                    
    if  (value  !=  aShowExportExcel)
                    
    {
                        
    this .ViewState[ " ShowExportExcel " =  value;
                        
    if  ( base .Initialized)
                        
    {
                            
    base .RequiresDataBinding  =   true ;
                        }

                    }

                }

            }

    声明两个LinkButton控件btnExportWord,btnExport,分别用于点击导出Excel和点击导出word,并在控件的OnInit事件中初始化两个控件

    声明两个LinkButton,并在控件的OnInit中初始化
       LinkButton btnExportWord;
            LinkButton btnExport; 
    protected   override   void  OnInit(EventArgs e)
            
    {
                
    this .EnableViewState  =   true ;


                btnExport 
    =   new  LinkButton();
                btnExport.CommandName 
    =   " ExportToExcel " ;
                btnExport.EnableViewState 
    =   true ;
                btnExport.Text 
    =   " 导出Excel " ;

                btnExportWord 
    =   new  LinkButton();
                btnExportWord.CommandName 
    =   " ExportToWord " ;
                btnExportWord.EnableViewState 
    =   true ;
                btnExportWord.Text 
    =   " 导出Word " ;
     
    base .OnInit(e);
            }


    将两个LinkButton添加到GridView子控件中。

      protected   override   int  CreateChildControls(System.Collections.IEnumerable dataSource,  bool  dataBinding)  {
                
    int  res  =   base .CreateChildControls(dataSource, dataBinding);
                    
    try
                    
    {
                        GridViewRow row 
    =   new  GridViewRow( 0 0 , DataControlRowType.Pager, DataControlRowState.Normal);  TableCell cell2  =   new  TableCell();
                        cell2.HorizontalAlign 
    =  HorizontalAlign.Right;
                        cell2.Wrap 
    =   false if  ( this .ShowExportExcel  ==   true )
                        
    {
                            l1 
    =   new  Literal();
                            l1.Text 
    =   "  [ " ;
                            cell2.Controls.Add(l1);
                            cell2.Controls.Add(btnExport);
                            l1 
    =   new  Literal();
                            l1.Text 
    =   " " ;
                            cell2.Controls.Add(l1);
                        }


                        
    if  ( this .ShowExportWord  ==   true )
                        
    {
                            l1 
    =   new  Literal();
                            l1.Text 
    =   "  [ " ;
                            cell2.Controls.Add(l1);
                            cell2.Controls.Add(btnExportWord);
                            l1 
    =   new  Literal();
                            l1.Text 
    =   " " ;
                            cell2.Controls.Add(l1);
                        }
     r.Cells.Add(cell2);
                        
    this .Controls[ 0 ].Controls.AddAt( 0 , row);
                    }

                    
    catch
                    
    {
                    }

                }

                
    return  res;
            }

    在导出的时候,我们希望一些列不被导出,如修改,删除这样的列,因此我们添加了这样的一个属性

    用于指定不被导出列,列名之间用,隔开
       string  _UnExportedColumnNames  =   "" ;
            [
      Description(
    " 不导出的数据列集合,将HeaderText用,隔开 " ),
      Category(
    " 扩展 " ),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
            PersistenceMode(PersistenceMode.InnerProperty)

      ]
            
    public   string  UnExportedColumnNames
            
    {
                
    get
                
    {
                    
    return  _UnExportedColumnNames;
                }

                
    set
                
    {
                    _UnExportedColumnNames 
    =  value;
                }

            }

    在导出的时候,原来的GridView列表中会有一些LinkButton或者DropDownList控件,导出的时候,我们也希望将其换成纯文本,用下面这个函数可以完成这个目的

    用于将GridView中的LinkButton和DropDownList转换成文本的方法
      private   void  DisableControls(Control gv)
            
    {

                LinkButton lb 
    =   new  LinkButton();

                Literal l 
    =   new  Literal();

                
    string  name  =  String.Empty;

                
    for  ( int  i  =   0 ; i  <  gv.Controls.Count; i ++ )
                
    {

                    
    if  (gv.Controls[i].GetType()  ==   typeof (LinkButton))
                    
    {

                        l.Text 
    =  (gv.Controls[i]  as  LinkButton).Text;

                        gv.Controls.Remove(gv.Controls[i]);

                        gv.Controls.AddAt(i, l);

                    }

                    
    else   if  (gv.Controls[i].GetType()  ==   typeof (DropDownList))
                    
    {
                        l.Text 
    =  (gv.Controls[i]  as  DropDownList).SelectedItem.Text;

                        gv.Controls.Remove(gv.Controls[i]);

                        gv.Controls.AddAt(i, l);

                    }


                    
    if  (gv.Controls[i].HasControls())
                    
    {
                        DisableControls(gv.Controls[i]);
                    }


                }

            }

    下面是处理ItemCommand,将GridView导出的代码

    处理OnRowCommand事件,将GridView数据导出到Excel和Word
       protected   override   void  OnRowCommand(GridViewCommandEventArgs e)
            
    {
                
    base .OnRowCommand(e);
                
    if  (e.CommandName  ==   " ExportToExcel " )
                
    {
                    
    string [] ss  =  UnExportedColumnNames.Split( ' , ' );
                    System.Collections.Generic.List
    < string >  list  =   new  System.Collections.Generic.List < string > ();

                    
    foreach  ( string  s  in  ss)
                    
    {
                        
    if  (s  !=   " , " )
                        
    {
                            list.Add(s);
                        }

                    }

                    ShowToolBar 
    =   false ;
                    
    this .AllowSorting  =   false ;
                    HttpContext.Current.Response.Clear();

                    HttpContext.Current.Response.AddHeader(
    " content-disposition " ,
                    
    " attachment;filename= "   +  ExcelFileName  +   " .xls " );

                    HttpContext.Current.Response.Charset 
    =   " GB2312 " ;
                    HttpContext.Current.Response.ContentEncoding 
    =  System.Text.Encoding.GetEncoding( " GB2312 " ); // 设置输出流为简体中文
                    HttpContext.Current.Response.ContentType  =   " application/ms-excel " ;


                    System.IO.StringWriter stringWrite 
    =   new  System.IO.StringWriter();

                    System.Web.UI.HtmlTextWriter htmlWrite 
    =
                    
    new  HtmlTextWriter(stringWrite);

                    
    bool  showCheckAll  =  ShowCheckAll;
                    
    this .ShowCheckAll  =   false ;
                    
    this .AllowPaging  =   false ;
                    OnBind();
                    DisableControls(
    this );
                    
    foreach  (DataControlField c  in   this .Columns)
                    
    {
                        
    if  (list.Contains(c.HeaderText)  &&   ! string .IsNullOrEmpty(c.HeaderText))
                        
    {
                            c.Visible 
    =   false ;
                        }

                    }

                    
    this .RenderControl(htmlWrite);
                    
    string  content  =  System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(),  " (<a[^>]+>)|(</a>) " "" );
                    HttpContext.Current.Response.Write(content);

                    HttpContext.Current.Response.End();

                    
    this .AllowPaging  =   true ;
                    
    this .AllowSorting  =   true ;
                    ShowToolBar 
    =   true ;
                    
    this .ShowCheckAll  =  showCheckAll;
                    OnBind();
                }

                
    else   if  (e.CommandName  ==   " ExportToWord " )
                
    {
                    
    string [] ss  =  UnExportedColumnNames.Split( ' , ' );
                    System.Collections.Generic.List
    < string >  list  =   new  System.Collections.Generic.List < string > ();

                    
    foreach  ( string  s  in  ss)
                    
    {
                        
    if  (s  !=   " , " )
                        
    {
                            list.Add(s);
                        }

                    }

                    ShowToolBar 
    =   false ;
                    
    this .AllowSorting  =   false ;
                    HttpContext.Current.Response.Clear();

                    HttpContext.Current.Response.AddHeader(
    " content-disposition " ,
                    
    " attachment;filename= "   +  ExcelFileName  +   " .doc " );

                    HttpContext.Current.Response.Charset 
    =   " GB2312 " ;
                    HttpContext.Current.Response.ContentEncoding 
    =  System.Text.Encoding.GetEncoding( " GB2312 " ); // 设置输出流为简体中文
                    HttpContext.Current.Response.ContentType  =   " application/ms-word " ;


                    System.IO.StringWriter stringWrite 
    =   new  System.IO.StringWriter();

                    System.Web.UI.HtmlTextWriter htmlWrite 
    =
                    
    new  HtmlTextWriter(stringWrite);

                    
    bool  showCheckAll  =  ShowCheckAll;
                    
    this .ShowCheckAll  =   false ;
                    
    this .AllowPaging  =   false ;
                    OnBind();

                    DisableControls(
    this );
                    
    foreach  (DataControlField c  in   this .Columns)
                    
    {
                        
    if  (list.Contains(c.HeaderText)  &&   ! string .IsNullOrEmpty(c.HeaderText))
                        
    {
                            c.Visible 
    =   false ;
                        }

                    }

                    
    this .RenderControl(htmlWrite);
                    
    string  content  =  System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(),  " (<a[^>]+>)|(</a>) " "" );
                    HttpContext.Current.Response.Write(content);

                    HttpContext.Current.Response.End();

                    
    this .AllowPaging  =   true ;
                    
    this .AllowSorting  =   true ;
                    ShowToolBar 
    =   true ;
                    ShowCheckAll 
    =  showCheckAll;
                    OnBind();
                }

            }


    使 用的时候,只要指定ShowExportExcel=True,ShowExportWord=True就自动出现导出Word和导出Excel的按钮 了,点击自动会将GridView中的数据导出到Word或者Excel中了,如果原GridView是多页的,那也会自动将全部数据(而不是当前页的数 据)导出,而且会剔除原来数据中的一些超级链接。使用起来相当简单,效果页非常好。

     

    展开全文
  • c#生成word文档

    2008-11-20 08:46:19
    c#生成word文档的个各种方法进行了详细介绍
  • C# 生成Word文档

    千次阅读 2019-03-04 16:45:52
    C#生成Word文档,实际尝试了一种可行的方法,记录如下: 1. 添加引用 Microsoft.Office.Interop.Word.dll,这个文件有多种版本,我选了11.0的,链接:...

    C#生成Word文档,实际尝试了一种可行的方法,记录如下:

    1. 添加引用

       Microsoft.Office.Interop.Word.dll,这个文件有多种版本,我选了11.0的,链接:https://download.csdn.net/download/zhouyingge1104/10992883

    2. 组织代码

    using Microsoft.Office.Interop.Word;
    
    //...
    
    Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();           
    winword.Visible = false;
    
    object missing = System.Reflection.Missing.Value;
    
    Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
    
    //页边距
    document.PageSetup.LeftMargin = 40; //1.41CM
    document.PageSetup.RightMargin = 40;
    document.PageSetup.TopMargin = 40;
    document.PageSetup.BottomMargin = 40;
    
    //页眉
    foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
    {
        //Get the header range and add the header details.
        Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
        headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
        headerRange.Font.Size = 10;
        headerRange.Text = "Header text goes here";
    }
    
    //页脚
    foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
    {
        Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
        footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
        footerRange.Font.Size = 10;
        footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        footerRange.Text = "Footer text goes here";
    }
    
    //添加内容
    document.Content.SetRange(0, 0);
    document.Content.Text = "检测报告 " + Environment.NewLine;
              
    //添加段落		  
    Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
    para1.Range.Text = "Para 1 text";
    para1.Range.InsertParagraphAfter();
    
    Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
    para2.Range.Text = "Para 2 text";
    para2.Range.InsertParagraphAfter();
                
    //表格
    Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);
                    
    firstTable.Borders.Enable = 1;
    foreach (Row row in firstTable.Rows)
    {
        foreach (Cell cell in row.Cells)
        {
            //表头
            if (cell.RowIndex == 1)
            {
                cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                cell.Range.Font.Bold = 1;
                cell.Range.Font.Name = "verdana";
                cell.Range.Font.Size = 10;
                cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            }
            //行
            else
            {
                cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
            }
        
    }
                    
    //保存
    string fName = "c://export.docx";
                    
    document.SaveAs(fName);  
    document.Close(ref missing, ref missing, ref missing);
    document = null;
    
    winword.Quit(ref missing, ref missing, ref missing);
    winword = null;
    
    //打开文件
    System.Diagnostics.Process.Start(fName);
    

    效果:

    参考:https://www.c-sharpcorner.com/UploadFile/muralidharan.d/how-to-create-word-document-using-C-Sharp/

     

    展开全文
  • C#生成word压缩下载

    2018-01-15 09:31:10
    C#生成word压缩下载 1.利用Aspose工具  在网上找一个 Aspose.Words.dll,下载后引用到项目中。 2.利用word生成我们需要的模板如下:  域的使用,本人对域开始不明白是什么东西,浪费了很多时间。这次就多...
    C#生成word压缩下载

    1.利用Aspose工具
      在网上找一个 Aspose.Words.dll ,下载后引用到项目中。
    2.利用word生成我们需要的模板如下:
      域的使用,本人对域开始不明白是什么东西,浪费了很多时间。这次就多占了几张图片,方便读者的理解。

      3.首页就一个按钮我是通过ajax下载的
         js代码
     
      4.后天页面


     源码下载 http://download.csdn.net/download/abc2222753/10205540

    展开全文
  • C#生成word文档 、word转pdf、合并pdf文件等 在系统开发中经常会有用户需求涉及到基于模板导出word文档、pdf文档,或者把几个文件合并成一个进行导出预览等,他们所说需求不一样,但在功能实现上却是相同的。由于...

    C#生成word文档 、word转pdf、合并pdf文件等

    在系统开发中经常会有用户需求涉及到基于模板导出word文档、pdf文档,或者把几个文件合并成一个进行导出预览等,他们所说需求不一样,但在功能实现上却是相同的。由于前期在使用时对pdf涉及的不太多,所以在文件导出时都是用的word转pdf形式。
    备注:在当前文章中所涉及到的模板均为.doc文件。

    需求描述

    用户根据表单填写基本信息,需要单个或者批量导出信息到word文档中。
    模板准备:
    1.空模板.doc //作为合并文件时的模板使用
    2.表单模板.doc //导出word模板

    代码如下:

    using Aspose.Words;
    using iTextSharp.text.pdf;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    
    public string HelloWorld()
            {
                var result = new { statue = "fail", url = "" };
                try
                {
                    Student bll = new Student();
                    string tempPath = HttpContext.Current.Server.MapPath("~/");//系统部署地址
    
                    #region 创建文件夹
    
                    List<string> li = new List<string>();
                    List<Student> list = GetStudentData();
                    foreach (Student model in list)
                    {
                        Document doc = new Document(tempPath + "表单模板.doc");//加载模板
                        string fName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + model.name + ".doc";
                        string savePath = tempPath + fName;//文件保存路径
                        //根据word中的标签赋值
                        doc.Range.Bookmarks["NAME"].Text = "张三";
                        doc.Range.Bookmarks["SEX"].Text = "男";
                        doc.Range.Bookmarks["AGE"].Text = "18";
    
                        doc.Save(savePath, SaveFormat.Doc);
                        DOCConvertToPDF(savePath, savePath.Replace(".doc", ".pdf"));
                        li.Add(savePath.Replace(".doc", ".pdf"));//生成附件的list集合
                    }
                    #endregion 创建文件夹
                    //保存文件路径
                    string sPath = tempPath + "_导出基本信息.doc";
                    string pdf_path = sPath.Replace(".doc", ".pdf");
                    DOCConvertToPDF(tempPath + "空模板.doc", pdf_path);
                    MergePDFFiles(li.ToArray(), pdf_path);//合并文件
    
                    //删除转换后的文件
                    foreach (PdfModel model in mergeFile_temp)
                    {
                        model.pdf.Dispose();
                        File.Delete(model.url);//删除临时文件
                        File.Delete(model.url.Replace(".pdf", ".word"));
                    }
    
                    result = new { statue = "success", url = pdf_path };
                }
                catch (Exception ex)
                {
                }
                return JsonConvert.SerializeObject(result); ;
            }
    
            /// <summary> 合并PDF </summary>  
            /// <param name="fileList">PDF文件集合</param>  
            /// <param name="outMergeFile">合并文件名</param>  
            /// 
            public static void MergePDFFiles(string[] fileList, string outMergeFile)
            {
                PdfReader reader;
                iTextSharp.text.Rectangle re;
                PdfDictionary pd;
                //List<PdfReader> readerList = new List<PdfReader>();//记录合并PDF集合  
                iTextSharp.text.Document document = new iTextSharp.text.Document();
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
                document.Open();
    
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;
                for (int i = 0; i < fileList.Length; i++)
                {
                    if (!string.IsNullOrEmpty(fileList[i]))
                    {
                        reader = new PdfReader(fileList[i]);
                        PdfModel model = new PdfModel();
                        model.pdf = reader;
                        model.url = fileList[i];
                        mergeFile_temp.Add(model);
    
                        int iPageNum = reader.NumberOfPages;
                        for (int j = 1; j <= iPageNum; j++)
                        {
                            //获取Reader的pdf页的打印方向
                            re = reader.GetPageSize(reader.GetPageN(j));
                            //设置合并pdf的打印方向
                            document.SetPageSize(re);
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            cb.AddTemplate(newPage, 0, 0);
                        }
                        //reader.Dispose();
                        //readerList.Add(reader);
                    }
                }
                document.Close();
                //Process.Start(outMergeFile);//预览
            }
    
    
            private static bool DOCConvertToPDF(string sourcePath, string targetPath)
            {
                bool result;
                try
                {
                    Aspose.Words.Document document = new Aspose.Words.Document(sourcePath);
                    document.Save(targetPath, Aspose.Words.SaveFormat.Pdf);
                    result = true;
                }
                catch (Exception ex)
                {
                    result = false;
                }
                return result;
            }
    
            public static List<Student> GetStudentData()
            {
    
                List<Student> list = new List<Student>();
    
                for (int index = 0; index < 3; index++)
                {
                    Student model = new Student();
                    model.name = "张三_" + index;
                    model.sex = "男-" + index;
                    model.age = index.ToString();
                    list.Add(model);
                }
                return list;
            }
    //访问实体类
    public class Student
        {
            /// <summary>
            /// 姓名
            /// </summary>
            public string name
            {
                set;
                get;
            }
            /// <summary>
            /// 性别
            /// </summary>
            public string sex
            {
                set;
                get;
            }
            /// <summary>
            /// 年龄
            /// </summary>
            public string age
            {
                set;
                get;
            }
    
        }
        public class PdfModel
        {
            public PdfReader pdf
            {
                set;
                get;
            }
            public string url
            {
                set;
                get;
            }
        }
    
    ... prompt'''

    文章中所涉及的模板为:
    这里写图片描述

    生成的文件格式为:
    这里写图片描述

    关于引用文件暂时无法上传。
    关于合并文件的暂时没有找到好的方法,都先凑合着用吧。

    展开全文
  • C# 生成Word文件并写入字符串.rar Crack8_编程小组[K.8] QQ吻's Blog http://qqhack8.blog.163.com
  • C#生成word和excel

    2011-12-13 11:09:39
    自己写的用C#语言生成word形式的部分考试安排页面和excel文档,并能导出
  • 源码 有1:asp.net 网页下载的word 给html串 生成相应的word下载到本地。 2:winform 生成word 按自己的格式 生成(需要按自己的格式写生成规则)
  • C#生成带饼图和柱状图在word2007文档 基于gltide分享上修改整理
  • C#生成word报告

    千次阅读 2019-07-06 11:16:48
    最近项目有个小需求,简单来说就是在C#环境中自动生成word分析报告。 实现思路:先设计一个报告模板,根据需要将其中的部分内容进行替换,模板可以使用书签和文字标识两种,如果要替换的内容不是很多采用文字标识就...
  • c#.net 生成word 内函表格制作 字体添加修改
  • C#开发,自动生成Word,并可以对添加的文字标记书签,书签自定义

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 18,750
精华内容 7,500
关键字:

c#生成word

c# 订阅