c#生成WORD

原文出处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是多页的,那也会自动将全部数据(而不是当前页的数 据)导出,而且会剔除原来数据中的一些超级链接。使用起来相当简单,效果页非常好。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值