首先引入类库,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 = "你好\n\n\r";
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 + "\r\n" + "创建成功";
}
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);
}
} 转http://develop.csai.cn/c/200612201000341746.htm
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 = "你好\n\n\r";
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 + "\r\n" + "创建成功";
}
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);
}
} 转http://develop.csai.cn/c/200612201000341746.htm
解决方案 »
- 高手们。帮忙看一下。。。。。。该一下。。。。。。
- 网站统计,如果从IIS日志中取出准确的访客量(也就是相当于取到独立IP的数量)..
- WinForm 怎样连结通过路由器连起来的另一台机子上的access数据库
- 怎样把获取的屏幕图片录成视频? C#
- 这样的运算用c#如何编写:1-1/2+1/3-1/4……+1/99-1/100 (我已编写了一个,但存在着问题,望有人能给改正。谢谢!@_@)
- C#事件延迟问题
- VS2005下PerformanceCounter的使用
- winFom下怎么获取当前选中的dataGrid行数据
- 问一个存储过程,请教
- 给出日期,如何计算这个日期是本年的第几个周?
- 图片合成视频的方法(C#或Delphi代码)
- ***.Click += new EventHandler(this.del_Click)事件无法响应,为何?
一是在编译的时候提示这个信息:方法“Microsoft.Office.Interop.Word._Document.Close(ref object, ref object, ref object)”和非方法“Microsoft.Office.Interop.Word.DocumentEvents2_Event.Close”之间存在二义性。将使用方法组。 D:\My Documents\Visual Studio 2005\Projects\PrintDoc\PrintDoc\Form1.cs 46 27 PrintDoc
二是在第一次运行document.open时正常,第二次运行document.open时出现异常:RPC 服务器不可用。 (异常来自 HRESULT:0x800706BA)
未处理 System.Runtime.InteropServices.COMException
Message="RPC 服务器不可用。 (异常来自 HRESULT:0x800706BA)"
Source="Microsoft.Office.Interop.Word"
ErrorCode=-2147023174
StackTrace:
在 Microsoft.Office.Interop.Word.ApplicationClass.get_Documents()
在 PrintDoc.Form1.OpenWord() 位置 D:\My Documents\Visual Studio 2005\Projects\PrintDoc\PrintDoc\Form1.cs:行号 38
在 PrintDoc.Form1.button1_Click(Object sender, EventArgs e) 位置 D:\My Documents\Visual Studio 2005\Projects\PrintDoc\PrintDoc\Form1.cs:行号 25
在 System.Windows.Forms.Control.OnClick(EventArgs e)
在 System.Windows.Forms.Button.OnClick(EventArgs e)
在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
在 System.Windows.Forms.Control.WndProc(Message& m)
在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
在 System.Windows.Forms.Button.WndProc(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.Run(Form mainForm)
在 PrintDoc.Program.Main() 位置 D:\My Documents\Visual Studio 2005\Projects\PrintDoc\PrintDoc\Program.cs:行号 17
在 System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ThreadHelper.ThreadStart()OpenFileDialog vaddress = new OpenFileDialog();
vaddress.DefaultExt = "*.mdb";
vaddress.Filter = "mdb文件 (*.mdb)|*.mdb|所有文件 (*.*)|*.*";
vaddress.FilterIndex = 1;
vaddress.DefaultExt = "*.mdb";
vaddress.Multiselect = false;
vaddress.Title = "浏览";
if (vaddress.ShowDialog() == DialogResult.OK)
this.textBox_Add.Text = vaddress.FileName;
vaddress.Dispose();
有这个时间不如看看智能文档的资料!!
还有
用C#来搞office简直是自虐啊 用vb好多了
为什么是"自虐",vb和c#语义结构都清楚吗?不要告诉我是从c#转到vb去的.
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using Graph = Microsoft.Office.Interop.Graph;namespace NWord
{
/// <summary>
/// 功能描述:操作word文件
/// 作者:--
/// 使用说明:在工程中添加Word 11.0对象库的引用。该模块在office2003基础上开发。
/// </summary>
public class C_Word
{
#region Variables
private string strwordfilename;//文件名
private string strwordfilepath;//文件路径
private bool wordvisible = false;//Word文件操作是否可见
Word._Application WordApp = new Word.Application();
Word._Document WordDoc;
object missing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc";
#endregion #region Properties
/// <summary>
/// word文件名
/// </summary>
public string WordFileName
{
get { return strwordfilename; }
} /// <summary>
/// word文件路径
/// </summary>
public string WordFilePath
{
get { return strwordfilepath; }
}
#endregion /// <summary>
/// 构造word对象
/// </summary>
public C_Word() { } /// <summary>
/// 构造word对象
/// </summary>
/// <param name="strfullfilepath">word文件全路径</param>
public C_Word(string strfullfilepath)
{
WordApp.Visible = false;
strwordfilename = Path.GetFileName(strfullfilepath);
strwordfilepath = Path.GetDirectoryName(strfullfilepath);
CreateWordFile(strfullfilepath);
} /// <summary>
/// 构造word对象
/// </summary>
/// <param name="strfullfilepath">word文件全路径</param>
/// <param name="overwrite">是否覆盖现有word文件</param>
public C_Word(string strfullfilepath, bool overwrite)
{
strwordfilename = Path.GetFileName(strfullfilepath);
strwordfilepath = Path.GetDirectoryName(strfullfilepath);
WordApp.Visible = wordvisible;
if (overwrite || !File.Exists(strfullfilepath))
{
CreateWordFile(strfullfilepath);
}
else
{
this.Open(strfullfilepath);
}
} /// <summary>
/// 打开word文件
/// </summary>
/// <param name="strfilepath">文件路径</param>
public void Open(string strfilepath)
{
object filepath = strfilepath;
object wrdvisible = wordvisible;
//WordApp.Documents.Add(ref filepath, ref missing, ref missing, ref wrdvisible); WordApp.Documents.Open(ref filepath, ref missing, ref missing, ref missing, ref missing
, ref missing, ref missing, ref missing, ref missing
, ref missing, ref missing, ref wrdvisible, ref missing
, ref missing, ref missing, ref missing); WordDoc = WordApp.Documents.Open(ref filepath,
ref missing, ref wrdvisible, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref wrdvisible,
ref missing, ref missing, ref missing, ref missing);
} /// <summary>
/// 新建word文件
/// </summary>
/// <param name="strfullfilepath">word文件路径</param>
private void CreateWordFile(string strfullfilepath)
{
object ofilename = strfullfilepath;
WordDoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); //验证路径
if (!Directory.Exists(Path.GetDirectoryName(strfullfilepath))) return;
if (Path.GetExtension(strfullfilepath).ToLower() != ".doc") return; try
{
if (File.Exists(strfullfilepath)) File.Delete(strfullfilepath);
WordApp.ActiveDocument.SaveAs(ref ofilename,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing);
return;
}
catch
{
return;
}
} /// <summary>
/// 从模版创建word文件
/// </summary>
/// <param name="strdotpath">word模版路径</param>
/// <param name="strdocpath">word文件路径</param>
public void CreateFileFromDot(string strdotpath,string strdocpath)
{
object filepath = strdotpath;
object owordfile = strdocpath; if (File.Exists(strdocpath))//删除已存在的文件
{
File.Delete(strdocpath);
} WordApp.Documents.Add(ref filepath, ref missing, ref missing, ref missing);
WordApp.ActiveDocument.SaveAs(ref owordfile,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing); this.Open(strdocpath); strwordfilepath = Path.GetDirectoryName(strdotpath);
strwordfilename = Path.GetFileName(strdocpath);
} /// <summary>
/// 向word结尾插入1行数据,不会换行
/// </summary>
/// <param name="strline">插入的字符串</param>
public void WriteLine(string strline)
{
object fileName = WordFilePath + WordFileName;
object bvisible = true; Word.Range wrdRng = WordDoc.Books.get_Item(ref oEndOfDoc).Range;
wrdRng.InsertAfter(strline);
this.Save();
} /// <summary>
/// 将书签更新成字符串
/// </summary>
/// <param name="bookName">书签名</param>
/// <param name="newText">更新字符串</param>
public void UpdateBook(string bookName, string newText)
{
object name = bookName;
Word.Range rng = WordApp.ActiveDocument.Books.get_Item(ref name).Range;
rng.Text = newText;
object range = rng;
WordApp.ActiveDocument.Books.Add(bookName, ref range);
this.Save();
} /// <summary>
/// 将书签更新成字符串
/// </summary>
/// <param name="book">word书签</param>
/// <param name="newText">更新字符串</param>
public void UpdateBook(Word.Book book, string newText)
{
object rng = book.Range;
string bookName = book.Name;
book.Range.Text = newText;
WordApp.ActiveDocument.Books.Add(bookName, ref rng);
this.Save();
}
/// <summary>
/// 更改某表的某个单元格的内容
/// </summary>
/// <param name="tableID">table id</param>
/// <param name="lineID">行id</param>
/// <param name="columnID">列id</param>
/// <param name="context">更新字符串</param>
public void UpdateTableContent(int tableID, int lineID, int columnID, string context)
{
Word.Table tbl = WordApp.ActiveDocument.Tables[tableID];
tbl.Cell(lineID, columnID).Range.Text = context;
this.Save();
} /// <summary>
/// 插入图表
/// </summary>
/// <param name="strbook">书签名</param>
/// <param name="dtsheet">图表数据源datatable</param>
/// <param name="xlcharttype">图表格式</param>
public void InsertChart(string strbook, DataTable dtsheet,Graph.XlChartType xlcharttype)
{
int i, j; Graph.Chart wrdChart;
Graph.Axis axis;
object oClassType = "MSGraph.Chart.8";
object book = strbook; //在指定的书签位置插入图表
Word.Range wrdRng = WordDoc.Books.get_Item(ref book).Range; //初始化一张图表
wrdChart = (Graph.Chart)wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing).OLEFormat.Object;
//wrdChart.Application.Visible = false; wrdChart.Application.PlotBy = Graph.XlRowCol.xlColumns;//根据Y轴来画图表
//改变图表格式
wrdChart.ChartType = xlcharttype; axis = (Graph.Axis)wrdChart.Axes(1, 1);//设置X轴的属性
wrdChart.Application.DataSheet.Cells.Clear();//清空表格的初始数据 //填充图表,起始的行号和列号都是1
for (i = 0; i < dtsheet.Columns.Count; i++)//初始化列名
{
wrdChart.Application.DataSheet.Cells[1, i + 1] = dtsheet.Columns[i].ColumnName;
}
for (i = 0; i < dtsheet.Rows.Count; i++)//填充数据
{
for (j = 0; j < dtsheet.Columns.Count; j++)
{
wrdChart.Application.DataSheet.Cells[i + 2, j + 1] = dtsheet.Rows[i][j].ToString().Replace("9999999", "100ys");
}
} //axis.MaximumScale = 1;//X轴最大刻度
//axis.MajorUnit = 0.1;
wrdChart.Legend.Delete();
wrdChart.Width = 500; //wrdChart.Height = 666;
//oShape.Height = oWord.InchesToPoints(3.57f); //更新图表并保存退出
wrdChart.Application.Update();
wrdChart.Application.Quit();
this.Save();
} /// <summary>
/// 清空文档
/// </summary>
public void Clear()
{
object Unit = (int)Word.WdUnits.wdCharacter;
object Count = 1;
WordApp.Selection.WholeStory();
WordApp.Selection.Delete(ref Unit, ref Count);
this.Save();
} /// <summary>
/// 另存为
/// </summary>
/// <param name="strFileName">目标文件路径</param>
public void SaveAs(string strFileName)
{
object fileName = strFileName;
WordApp.ActiveDocument.SaveAs(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
} /// <summary>
/// 转到指定的标签处
/// </summary>
/// <param name="strBookMarkName">标签名</param>
public void GotoBookMark(string strBookMarkName)
{
object Book = (int)Word.WdGoToItem.wdGoToBook;
object NameBookMark = strBookMarkName;
WordApp.Selection.GoTo(ref Book, ref missing, ref missing, ref NameBookMark);
} /// <summary>
/// 删除指定的文本
/// </summary>
/// <param name="text">被删除的文本</param>
public void DeleteText(string text)
{ object findText = text;
object replaceWith = "";
object replaceAll = Word.WdReplace.wdReplaceAll;
this.WordApp.Selection.Find.ClearFormatting();
this.WordApp.Selection.Find.Replacement.ClearFormatting();
this.WordApp.Selection.Find.Replacement.Text = "";
this.WordApp.Selection.Find.Execute(ref findText,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref replaceWith, ref replaceAll, ref missing, ref missing,
ref missing, ref missing); object unit = (int)Word.WdUnits.wdCharacter;
object count = 1;
this.WordApp.Selection.Delete(ref unit, ref count);
this.Save();
} /// <summary>
/// 保存当前word文档
/// </summary>
private void Save()
{
WordApp.ActiveDocument.Save();
} /// <summary>
/// 关闭Word文件,释放对象;最后一定要调用此函数,否则会引起异常
/// </summary>
public void Close()
{
try
{
WordApp.Application.Quit(ref missing, ref missing, ref missing);
if (WordApp != null)
{
WordApp = null;
}
}
catch
{ }
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
}
http://passport.csdn.net/UserLogin.aspx