using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Web;
using System.Data;
using System.Reflection;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Net;
namespace OfficeOperate {
public class WordOperate {
#region 动态生成Word文档并填充数据 /// <summary>
public static string CreateWordFile() {
string message =
"";
try { Object oMissing = System.Reflection.Missing.Value;
string dir = System.Web.HttpContext.Current.Server.MapPath(
"" );
if( !Directory.Exists( dir +
"//file" ) ) { Directory.CreateDirectory( dir +
"//file" ); }
string name = DateTime.Now.ToLongDateString() +
".doc";
object filename = dir +
"//file//" + name; Microsoft.Office.Interop.Word.Application WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing ); 添加页眉方法一:
if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView ) { WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView; } WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
string sHeader =
"页眉内容"; WordApp.Selection.HeaderFooter.LinkToPrevious =
false; WordApp.Selection.HeaderFooter.Range.Text = sHeader; WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
object count = 14;
object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine; WordApp.Selection.MoveDown(
ref WdLine,
ref count,
ref oMissing ); WordApp.Selection.TypeParagraph(); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3,
ref oMissing,
ref oMissing ); newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap; newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; newTable.Columns[1].Width = 100f; newTable.Columns[2].Width = 220f; newTable.Columns[3].Width = 105f; newTable.Cell( 1, 1 ).Range.Text =
"产品详细信息表"; newTable.Cell( 1, 1 ).Range.Bold = 2; newTable.Cell( 1, 1 ).Merge( newTable.Cell( 1, 3 ) ); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell( 2, 1 ).Range.Text =
"产品基本信息"; newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue; newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) ); WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell( 3, 1 ).Range.Text =
"品牌名称:"; newTable.Cell( 3, 2 ).Range.Text =
"BrandName"; newTable.Cell( 3, 3 ).Select();
object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
object moveCount = 5;
object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend; WordApp.Selection.MoveDown(
ref moveUnit,
ref moveCount,
ref moveExtend ); WordApp.Selection.Cells.Merge();
if( File.Exists( System.Web.HttpContext.Current.Server.MapPath(
"images//picture.jpg" ) ) ) {
string FileName = System.Web.HttpContext.Current.Server.MapPath(
"images//picture.jpg" );//图片所在路径
object LinkToFile =
false;
object SaveWithDocument =
true;
object Anchor = WordDoc.Application.Selection.Range; WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName,
ref LinkToFile,
ref SaveWithDocument,
ref Anchor ); WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f; WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f; } Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; newTable.Cell( 12, 1 ).Range.Text =
"产品特殊属性"; newTable.Cell( 12, 1 ).Merge( newTable.Cell( 12, 3 ) ); WordDoc.Content.Tables[1].Rows.Add(
ref oMissing ); WordDoc.Paragraphs.Last.Range.Text =
"文档创建时间:" + DateTime.Now.ToString(); WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; WordDoc.SaveAs(
ref filename,
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 ); WordDoc.Close(
ref oMissing,
ref oMissing,
ref oMissing ); WordApp.Quit(
ref oMissing,
ref oMissing,
ref oMissing ); message = name +
"文档生成成功"; }
catch { message =
"文件导出异常!"; }
return message; }
#endregion #region 创建并打开一个空的word文档进行编辑 /// <summary>
public static void OpenNewWordFileToEdit() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing ); }
#endregion #region 创建word文档 /// <summary>
public static string createWord() { Microsoft.Office.Interop.Word.Application WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); Document WordDoc;
string strContent =
"";
object strFileName = System.Web.HttpContext.Current.Server.MapPath(
"test.doc " );
if( System.IO.File.Exists( (
string)strFileName ) ) System.IO.File.Delete( (
string)strFileName ); Object oMissing = System.Reflection.Missing.Value; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing );
#region 将数据库中读取得数据写入到word文件中 strContent =
"你好/n/n/r "; WordDoc.Paragraphs.Last.Range.Text = strContent; strContent =
"这是测试程序 "; WordDoc.Paragraphs.Last.Range.Text = strContent;
#endregion WordDoc.SaveAs(
ref strFileName,
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 ); WordDoc.Close(
ref oMissing,
ref oMissing,
ref oMissing ); WordApp.Quit(
ref oMissing,
ref oMissing,
ref oMissing );
string message = strFileName +
"/r/n " +
"创建成功 ";
return message; }
#endregion #region 把Word文档装化为Html文件 /// <summary>
public static void WordToHtml(
string strFileName ) {
string saveFileName = strFileName + DateTime.Now.ToString(
"yyyy-MM-dd-HH-mm-ss" ) +
".html"; WordToHtml( strFileName, saveFileName ); } /// <summary>
public static void WordToHtml(
string strFileName,
string strSaveFileName ) { Microsoft.Office.Interop.Word.ApplicationClass WordApp; Microsoft.Office.Interop.Word.Document WordDoc; Object oMissing = System.Reflection.Missing.Value; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass();
object fileName = strFileName; WordDoc = WordApp.Documents.Open(
ref fileName,
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 ); Type wordType = WordApp.GetType(); Type docsType = WordApp.Documents.GetType(); Type docType = WordDoc.GetType();
object saveFileName = strSaveFileName; docType.InvokeMember(
"SaveAs", System.Reflection.BindingFlags.InvokeMethod,
null, WordDoc,
new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );
#region 其它格式: ///wdFormatHTML
#endregion WordDoc.Close(
ref oMissing,
ref oMissing,
ref oMissing ); WordApp.Quit(
ref oMissing,
ref oMissing,
ref oMissing ); }
#endregion #region 导入模板 /// <summary>
public static void ImportTemplate(
string filePath ) {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true;
object fileName = filePath; WordDoc = WordApp.Documents.Add(
ref fileName,
ref oMissing,
ref oMissing,
ref oMissing ); }
#endregion #region word中添加新表 /// <summary>
public static void AddTable() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing );
object start = 0;
object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(
ref start,
ref end ); WordDoc.Tables.Add( tableLocation, 3, 4,
ref oMissing,
ref oMissing ); }
#endregion #region 在表中插入新行 /// <summary>
public static void AddRow() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing );
object start = 0;
object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(
ref start,
ref end ); WordDoc.Tables.Add( tableLocation, 3, 4,
ref oMissing,
ref oMissing ); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
object beforeRow = newTable.Rows[1]; newTable.Rows.Add(
ref beforeRow ); }
#endregion #region 分离单元格 /// <summary>
public static void CombinationCell() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing );
object start = 0;
object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(
ref start,
ref end ); WordDoc.Tables.Add( tableLocation, 3, 4,
ref oMissing,
ref oMissing ); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
object beforeRow = newTable.Rows[1]; newTable.Rows.Add(
ref beforeRow ); Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 ); cell.Merge( newTable.Cell( 2, 2 ) ); }
#endregion #region 分离单元格 /// <summary>
public static void SeparateCell() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing );
object start = 0;
object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(
ref start,
ref end ); WordDoc.Tables.Add( tableLocation, 3, 4,
ref oMissing,
ref oMissing ); Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
object beforeRow = newTable.Rows[1]; newTable.Rows.Add(
ref beforeRow ); Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 ); cell.Merge( newTable.Cell( 1, 2 ) );
object Rownum = 2;
object Columnnum = 2; cell.Split(
ref Rownum,
ref Columnnum ); }
#endregion #region 通过段落控制插入Insert a paragraph at the beginning of the document. /// <summary>
public static void Insert() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass(); WordApp.Visible =
true; WordDoc = WordApp.Documents.Add(
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing ); Microsoft.Office.Interop.Word.Paragraph oPara1; oPara1 = WordDoc.Content.Paragraphs.Add(
ref oMissing ); oPara1.Range.Text =
"Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; oPara1.Range.InsertParagraphAfter(); }
#endregion #region word文档设置及获取光标位置 /// <summary>
public static void WordSet() {
object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application WordApp; Microsoft.Office.Interop.Word.Document WordDoc; WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass();
#region 文档格式设置 WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0; WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait; WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints(
float.Parse(
"2.54" ) ); WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints(
float.Parse(
"2.54" ) ); WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints(
float.Parse(
"3.17" ) ); WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints(
float.Parse(
"3.17" ) ); WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints(
float.Parse(
"0" ) ); WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints(
float.Parse(
"1.5" ) ); WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints(
float.Parse(
"1.75" ) ); WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints(
float.Parse(
"21" ) ); WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints(
float.Parse(
"29.7" ) ); WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin; WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin; WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage; WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0; WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0; WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop; WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0; WordApp.ActiveDocument.PageSetup.MirrorMargins = 0; WordApp.ActiveDocument.PageSetup.TwoPagesOnOne =
false; WordApp.ActiveDocument.PageSetup.BookFoldPrinting =
false; WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting =
false; WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1; WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft; WordApp.ActiveDocument.PageSetup.LinesPage = 40; WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;
#endregion #region 段落格式设定 WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints(
float.Parse(
"0" ) ); WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints(
float.Parse(
"0" ) ); WordApp.Selection.ParagraphFormat.SpaceBefore =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0; WordApp.Selection.ParagraphFormat.SpaceAfter =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0; WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle; WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify; WordApp.Selection.ParagraphFormat.WidowControl = 0; WordApp.Selection.ParagraphFormat.KeepWithNext = 0; WordApp.Selection.ParagraphFormat.KeepTogether = 0; WordApp.Selection.ParagraphFormat.PageBreakBefore = 0; WordApp.Selection.ParagraphFormat.NoLineNumber = 0; WordApp.Selection.ParagraphFormat.Hyphenation = 1; WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints(
float.Parse(
"0" ) ); WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText; WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.LineUnitBefore =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.LineUnitAfter =
float.Parse(
"0" ); WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1; WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0; WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1; WordApp.Selection.ParagraphFormat.WordWrap = 1; WordApp.Selection.ParagraphFormat.HangingPunctuation = 1; WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0; WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1; WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1; WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;
#endregion #region 字体格式设定 WordApp.Selection.Font.NameFarEast =
"华文中宋"; WordApp.Selection.Font.NameAscii =
"Times New Roman"; WordApp.Selection.Font.NameOther =
"Times New Roman"; WordApp.Selection.Font.Name =
"宋体"; WordApp.Selection.Font.Size =
float.Parse(
"14" ); WordApp.Selection.Font.Bold = 0; WordApp.Selection.Font.Italic = 0; WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone; WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; WordApp.Selection.Font.StrikeThrough = 0; WordApp.Selection.Font.DoubleStrikeThrough = 0; WordApp.Selection.Font.Outline = 0; WordApp.Selection.Font.Emboss = 0; WordApp.Selection.Font.Shadow = 0; WordApp.Selection.Font.Hidden = 0; WordApp.Selection.Font.SmallCaps = 0; WordApp.Selection.Font.AllCaps = 0; WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; WordApp.Selection.Font.Engrave = 0; WordApp.Selection.Font.Superscript = 0; WordApp.Selection.Font.Subscript = 0; WordApp.Selection.Font.Spacing =
float.Parse(
"0" ); WordApp.Selection.Font.Scaling = 100; WordApp.Selection.Font.Position = 0; WordApp.Selection.Font.Kerning =
float.Parse(
"1" ); WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone; WordApp.Selection.Font.DisableCharacterSpaceGrid =
false; WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;
#endregion #region 获取光标位置 get_Information WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber );
#endregion #region 光标移动 object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
object count = 3; WordApp.Selection.MoveEnd(
ref unit,
ref count ); WordApp.Selection.MoveUp(
ref unit,
ref count,
ref oMissing ); WordApp.Selection.Tables[1].Cell( 1, 1 ).Select();
object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;
object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
///extend对光标移动区域进行扩展选择
object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;
object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;
#endregion }
#endregion #region 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。 /// <summary>
public static string ReadWord_tableContentByCell(
string fileName,
int rowIndex,
int colIndex ) { ApplicationClass cls =
null; Document doc =
null; Table table =
null;
object missing = Missing.Value;
object path = fileName; cls =
new ApplicationClass();
try { doc = cls.Documents.Open (
ref path,
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 ); table = doc.Tables[1];
string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString(); text = text.Substring( 0, text.Length - 2 );
return text; }
catch( Exception ex ) {
return ex.Message; }
finally {
if( doc !=
null ) doc.Close(
ref missing,
ref missing,
ref missing ); cls.Quit(
ref missing,
ref missing,
ref missing ); } }
#endregion #region 修改word表格中指定单元格的数据 /// <summary>
public static bool UpdateWordTableByCell(
string fileName,
int rowIndex,
int colIndex,
string content ) { ApplicationClass cls =
null; Document doc =
null; Table table =
null;
object missing = Missing.Value;
object path = fileName; cls =
new ApplicationClass();
try { doc = cls.Documents.Open (
ref path,
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 ); table = doc.Tables[1]; table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();
return true; }
catch {
return false; }
finally {
if( doc !=
null ) { doc.Close(
ref missing,
ref missing,
ref missing ); cls.Quit(
ref missing,
ref missing,
ref missing ); } } }
#endregion #region 清楚word进程 /// <summary>
public static void KillWordProcess() { System.Diagnostics.Process[] myPs; myPs = System.Diagnostics.Process.GetProcesses();
foreach( System.Diagnostics.Process p
in myPs ) {
if( p.Id != 0 ) {
string myS =
"WINWORD.EXE" + p.ProcessName +
" ID:" + p.Id.ToString();
try {
if( p.Modules !=
null )
if( p.Modules.Count > 0 ) { System.Diagnostics.ProcessModule pm = p.Modules[0]; myS +=
"/n Modules[0].FileName:" + pm.FileName; myS +=
"/n Modules[0].ModuleName:" + pm.ModuleName; myS +=
"/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
if( pm.ModuleName.ToLower() ==
"winword.exe" ) p.Kill(); } }
catch { }
finally { ; } } } }
#endregion #region 清楚excel进程 /// <summary>
public static void KillExcelProcess() { System.Diagnostics.Process[] myPs; myPs = System.Diagnostics.Process.GetProcesses();
foreach( System.Diagnostics.Process p
in myPs ) {
if( p.Id != 0 ) {
string myS =
"excel.EXE" + p.ProcessName +
" ID:" + p.Id.ToString();
try {
if( p.Modules !=
null )
if( p.Modules.Count > 0 ) { System.Diagnostics.ProcessModule pm = p.Modules[0]; myS +=
"/n Modules[0].FileName:" + pm.FileName; myS +=
"/n Modules[0].ModuleName:" + pm.ModuleName; myS +=
"/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
if( pm.ModuleName.ToLower() ==
"excel.exe" ) p.Kill(); } }
catch { }
finally { ; } } } }
#endregion #region 网页内容或导入word或excel /// <summary>
public static void SaveOrOutData(
string url,
int num ) { WebRequest req = WebRequest.Create( url ); WebResponse resp = req.GetResponse(); StreamReader sr =
new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 );
string x = sr.ReadToEnd(); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(
"gb2312" );
string fName = DateTime.Now.ToString(
"yyyy-MM-dd-ss" );
if( num == 0 ) { fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding(
"gb2312" ) ) +
".doc"; System.Web.HttpContext.Current.Response.ContentType =
"application/ms-word"; }
else { fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding(
"gb2312" ) ) +
".xls"; System.Web.HttpContext.Current.Response.ContentType =
"application nd.xls"; } System.Web.HttpContext.Current.Response.AddHeader(
"content-disposition",
"attachment;filename=" + fName ); System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) ); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } /// <summary>
private static string getBodyContent(
string input ) {
string pattern = @
"<table.*?</table>"; Regex reg =
new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase ); Match mc = reg.Match( input );
string bodyContent =
"";
if( mc.Success ) { bodyContent = mc.Value; }
return bodyContent; }
#endregion #region 判断系统是否装excel /// <summary>
public static bool IsInstallExcel() { RegistryKey machineKey = Registry.LocalMachine;
if( IsInstallExcelByVersion(
"12.0", machineKey ) ) {
return true; }
if( IsInstallExcelByVersion(
"11.0", machineKey ) ) {
return true; }
return false; } /// <summary>
private static bool IsInstallExcelByVersion(
string strVersion, RegistryKey machineKey ) {
try { RegistryKey installKey = machineKey.OpenSubKey(
"Software" ).OpenSubKey(
"Microsoft" ).OpenSubKey(
"Office" ).OpenSubKey( strVersion ).OpenSubKey(
"Excel" ).OpenSubKey(
"InstallRoot" );
if( installKey ==
null ) {
return false; }
return true; }
catch {
return false; } }
#endregion #region 判断系统是否装word /// <summary>
public static bool IsInstallWord() { RegistryKey machineKey = Registry.LocalMachine;
if( IsInstallExcelByVersion(
"12.0", machineKey ) ) {
return true; }
if( IsInstallExcelByVersion(
"11.0", machineKey ) ) {
return true; }
return false; } /// <summary>
private static bool IsInstallWordByVersion(
string strVersion, RegistryKey machineKey ) {
try { RegistryKey installKey = machineKey.OpenSubKey(
"Software" ).OpenSubKey(
"Microsoft" ).OpenSubKey(
"Office" ).OpenSubKey( strVersion ).OpenSubKey(
"Word" ).OpenSubKey(
"InstallRoot" );
if( installKey ==
null ) {
return false; }
return true; }
catch {
return false; } }
#endregion } }