【小丸类库系列】Word操作类
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions; namespace OtaReportTool
{
public class WordHelper
{
#region 成员变量 private bool isWordVisible = false;
private object missing = Missing.Value;
private Application app;
private Document doc; #endregion 成员变量 #region 构造函数 /// <summary>
/// 构造函数,新建一个工作簿
/// </summary>
public WordHelper()
{
app = new Application();
app.Visible = isWordVisible;
doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
} /// <summary>
/// 构造函数,打开一个已有的工作簿
/// </summary>
/// <param name="fileName">Excel文件名</param>
public WordHelper(string fileName)
{
if (!File.Exists(fileName))
throw new Exception("指定路径的Word文件不存在!"); //创建Word进程
app = new Application();
app.Visible = isWordVisible; //打开Word文件
object objFileName = fileName;
object objIsWordVisible = isWordVisible;
object objIsWordReadOnly = true;
object objEncoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
doc = app.Documents.Open(ref objFileName,
ref missing, ref objIsWordReadOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref objEncoding, ref objIsWordVisible,
ref missing, ref missing, ref missing, ref missing);
doc.Activate(); //将视图从 页面视图 切换到 普通视图,避免因为分页计算而延迟word响应时间
if (doc.ActiveWindow.View.SplitSpecial == WdSpecialPane.wdPaneNone)
{
doc.ActiveWindow.ActivePane.View.Type = WdViewType.wdNormalView;
}
else
{
doc.ActiveWindow.View.Type = WdViewType.wdNormalView;
}
} #endregion 构造函数 #region 文本操作 /// <summary>
/// 设置字体
/// </summary>
/// <param name="sFontName"></param>
public void SetFont(string sFontName)
{
doc.Select();
app.Selection.Font.Name = sFontName;
} /// <summary>
/// 插入文本 Inserts the specified text.
/// </summary>
/// <param name="text"></param>
public void InsertText(string text)
{
app.Selection.TypeText(text);
} /// <summary>
/// Enter(换行) Inserts a new, blank paragraph.
/// </summary>
public void InsertLineBreak()
{
app.Selection.TypeParagraph();
} /// <summary>
/// 插入分页符
/// </summary>
public void InsertBreak()
{
Paragraph para = doc.Content.Paragraphs.Add(missing);
object pBreak = (int)WdBreakType.wdSectionBreakNextPage;
para.Range.InsertBreak(ref pBreak);
} /// <summary>
/// 插入图片(图片大小自适应)
/// </summary>
/// <param name="fileName">图片名(包含路径)</param>
public void InsertPic(string fileName)
{
object range = app.Selection.Range;
InsertPic(fileName, missing, missing, range);
} /// <summary>
/// 插入图片(带标题)
/// </summary>
/// <param name="fileName">图片名</param>
/// <param name="caption">标题</param>
public void InsertPic(string fileName, string caption)
{
object range = app.Selection.Range;
InsertPic(fileName, missing, missing, range, , , caption);
} /// <summary>
/// 插入图片
/// </summary>
/// <param name="fileName">图片名(包含路径)</param>
/// <param name="width">设置宽度</param>
/// <param name="height">设置高度</param>
public void InsertPic(string fileName, float width, float height)
{
object range = app.Selection.Range;
InsertPic(fileName, missing, missing, range, width, height);
} /// <summary>
/// 插入图片(带标题)
/// </summary>
/// <param name="fileName">图片名(包含路径)</param>
/// <param name="width">设置宽度</param>
/// <param name="height">设置高度<</param>
/// <param name="caption">标题或备注文字</param>
public void InsertPic(string fileName, float width, float height, string caption)
{
object range = app.Selection.Range;
InsertPic(fileName, missing, missing, range, width, height, caption);
} /// <summary>
/// 插入图片(带标题)
/// </summary>
public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height, string caption)
{
app.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
if (Width > )
{
app.Selection.InlineShapes[].Width = Width;
}
if (Height > )
{
app.Selection.InlineShapes[].Height = Height;
} object Label = WdCaptionLabelID.wdCaptionFigure;
object Title = caption;
object TitleAutoText = "";
object Position = WdCaptionPosition.wdCaptionPositionBelow;
object ExcludeLabel = true;
app.Selection.InsertCaption(ref Label, ref Title, ref TitleAutoText, ref Position, ref ExcludeLabel);
MoveRight();
} /// <summary>
/// Adds a picture to a document.
/// </summary>
/// <param name="FileName">Required String. The path and file name of the picture.</param>
/// <param name="LinkToFile">Optional Object. True to link the picture to the file from which it was created. False to make the picture an independent copy of the file. The default value is False.</param>
/// <param name="SaveWithDocument">Optional Object. True to save the linked picture with the document. The default value is False.</param>
/// <param name="Range">Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.</param>
/// <param name="Width">Sets the width of the specified object, in points. </param>
/// <param name="Height">Sets the height of the specified inline shape. </param>
public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height)
{
app.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
app.Selection.InlineShapes[].Width = Width;
app.Selection.InlineShapes[].Height = Height;
MoveRight();
} /// <summary>/// Adds a picture to a document.
/// </summary>
/// <param name="FileName">Required String. The path and file name of the picture.</param>
/// <param name="LinkToFile">Optional Object. True to link the picture to the file from which it was created. False to make the picture an independent copy of the file. The default value is False.</param>
/// <param name="SaveWithDocument">Optional Object. True to save the linked picture with the document. The default value is False.</param>
/// <param name="Range">Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.</param>
public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range)
{
app.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range);
} /// <summary>
/// 获取段落的文本
/// </summary>
/// <param name="index">段落编号</param>
/// <returns></returns>
public string Paragraph(int index)
{
Paragraph para = doc.Content.Paragraphs[index]; ///这是一个设定对应的某一段
return para.Range.Text;
} public void DeleteParagraph(int index)
{
Paragraph para = doc.Content.Paragraphs[index]; ///这是一个设定对应的某一段
para.Range.Delete();
return;
} public string Section(int index)
{
return doc.Sections[index].Range.Text;
} public void DeleteSection(int index)
{
Sections secs = doc.Sections;
Section sec = secs[index]; sec.Range.Delete();
return;
} /// <summary>
/// 替换文档中的文本
/// </summary>
/// <param name="oldString">原有内容</param>
/// <param name="newString">替换后的内容</param>
public void ReplaceString(string oldString, string newString)
{
doc.Content.Find.Text = oldString;
object FindText, ReplaceWith, ReplaceAll;
FindText = oldString;
ReplaceWith = newString;
ReplaceAll = WdReplace.wdReplaceAll;
doc.Content.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);
} /// <summary>
/// 获取word文档的纯文本
/// </summary>
/// <returns></returns>
public string GetText()
{
return doc.Content.Text;
} #endregion 文本操作 #region 格式操作 /// <summary>
/// 设置对齐方式
/// </summary>
/// <param name="rng"></param>
/// <param name="alignment"></param>
/// <returns></returns>
public WdParagraphAlignment SetAlignment(Range rng, Alignment alignment)
{
rng.ParagraphFormat.Alignment = SetAlignment(alignment);
return SetAlignment(alignment);
} public WdParagraphAlignment SetAlignment(Alignment alignment)
{
if (alignment == Alignment.居中)
{
return WdParagraphAlignment.wdAlignParagraphCenter;
}
else if (alignment == Alignment.左对齐)
{
return WdParagraphAlignment.wdAlignParagraphLeft;
}
else
{ return WdParagraphAlignment.wdAlignParagraphRight; }
} //字体格式设定
public void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)
{
wordFont.Name = font.Name;
wordFont.Size = font.Size;
if (font.Bold) { wordFont.Bold = ; }
if (font.Italic) { wordFont.Italic = ; }
if (font.Underline == true)
{
wordFont.Underline = WdUnderline.wdUnderlineNone;
}
wordFont.UnderlineColor = WdColor.wdColorAutomatic; if (font.Strikeout)
{
wordFont.StrikeThrough = ;//删除线
}
} public void SetCenterAlignment()
{
app.Selection.Range.ParagraphFormat.Alignment = SetAlignment(Alignment.居中);
} #endregion 格式操作 #region 表格操作 /// <summary>
/// 获取表格
/// </summary>
/// <param name="index">段落编号</param>
/// <returns></returns>
public Table Table(int index)
{
Table table = doc.Tables[index]; ///这是一个设定对应的某一段
return table;
} public string ReadTableContent(int tableIdx, int rowIdx, int colIdx)
{
return doc.Tables[tableIdx].Cell(rowIdx, colIdx).Range.Text.Trim('\r', '\a', '\n').Trim();
} public string ReadTableContent(Table table, int rowIdx, int colIdx)
{
try
{
return table.Cell(rowIdx, colIdx).Range.Text.Trim('\r', '\a', '\n').Trim();
}
catch (Exception)
{
return string.Empty;
}
} public int GetTableRowCount(int tableIdx)
{
return doc.Tables[tableIdx].Rows.Count;
} public Table GetTable(int tableIndex)
{
if (doc.Tables.Count >= tableIndex)
{
return doc.Tables[tableIndex];
}
return null;
} public Table InsertTableRow(Table table)
{
if (table != null)
{
table.Rows.Add();
} return table;
} public Table InsertTableColumn(Table table)
{
if (table != null)
{
table.Columns.Add();
}
return table;
} public Table InsertTableColumns(Table table, int columnCount)
{
for (int i = ; i < columnCount; i++)
{
table = InsertTableColumn(table);
}
return table;
} public Table DeleteTableRows(Table table, List<int> rowIndexs)
{
if (table != null)
{
foreach (var i in rowIndexs)
{
table = DeleteTableRow(table, i);
}
}
return table;
} public Table DeleteTableRow(Table table, int rowIndex)
{
try
{
if (table != null)
{
table.Rows[rowIndex].Delete();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
} return table;
} /// <summary>
/// 删除单元格
/// </summary>
/// <param name="table"></param>
/// <param name="rowIndex"></param>
/// <param name="columnIndex"></param>
/// <param name="shiftcells">删除类型</param>
/// wdDeleteCellsEntireColumn 3 Delete the entire column of cells from the table.
/// wdDeleteCellsEntireRow 2 Delete the entire row of cells from the table.
/// wdDeleteCellsShiftLeft 0 Shift remaining cells left in the row where the deletion occurred after a cell or range of cells has been deleted.
/// wdDeleteCellsShiftUp 1 Shift remaining cells up in the column where the deletion occurred after a cell or range of cells has been deleted.
/// <returns></returns>
public Table DeleteTableCell(Table table, int rowIndex, int columnIndex, int shiftcells)
{
try
{
if (table != null)
{
table.Cell(rowIndex, columnIndex).Delete(shiftcells);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
} return table;
} public Table DeleteTableColumn(Table table, int columnIndex)
{
try
{
if (table != null)
{
table.Columns[columnIndex].Delete();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
} return table;
} public bool WriteTableCellContent(Table table, int rowIndex, int colIndex, string content)
{
try
{
table.Cell(rowIndex, colIndex).Range.Delete();
table.Cell(rowIndex, colIndex).Range.Text = content;
}
catch (Exception exception)
{
return false;
}
return true;
} public bool DeleteTableCellContent(Table table, int rowIndex, int colIndex)
{
try
{
table.Cell(rowIndex, colIndex).Range.Delete();
}
catch (Exception exception)
{
return false;
}
return true;
} public int GetTableCount()
{
int tableCount = ;
try
{
tableCount = doc.Tables.Count;
}
catch (Exception exception)
{
}
return tableCount;
} public bool DeleteTable(int index)
{
try
{
doc.Tables[index].Delete();
}
catch (Exception exception)
{
return false;
}
return true;
} public bool DeleteTable(Table table)
{
try
{
table.Delete();
}
catch (Exception exception)
{
return false;
}
return true;
} public bool DeleteTables(List<int> tableIndexs)
{
try
{
if (tableIndexs.Count > )
{
foreach (var i in tableIndexs)
{
doc.Tables[i].Delete();
}
}
}
catch (Exception exception)
{
return false;
}
return true;
} public void MergeRowCells(int tableIndexs, int rowIndex)
{
try
{
doc.Tables[tableIndexs].Rows[rowIndex].Cells.Merge();
}
catch (Exception exception)
{
}
} public void MergeRowCells(Table table, int rowIndex)
{
try
{
table.Rows[rowIndex].Cells.Merge();
}
catch (Exception exception)
{
}
} public void MergeColumnCells(Table table, int columnIndex)
{
try
{
table.Columns[columnIndex].Cells.Merge();
}
catch (Exception exception)
{
}
} public void MergeCells(Table table, int rowIndex, int columnIndex, int rowIndex2, int columnIndex2)
{
try
{
table.Cell(rowIndex, columnIndex).Merge(table.Cell(rowIndex2, columnIndex2));
}
catch (Exception exception)
{
}
} public void MergeCells2(Table table, int rowIndex, int columnIndex, int length)
{
try
{
table.Cell(rowIndex, columnIndex).Select(); //选中一行
object moveUnit1 = WdUnits.wdLine;
object moveCount1 = length;
object moveExtend1 = WdMovementType.wdExtend;
app.Selection.MoveDown(ref moveUnit1, ref moveCount1, ref moveExtend1);
app.Selection.Cells.Merge();
}
catch (Exception exception)
{
}
} //插入表格 -
public bool InsertTable(System.Data.DataTable dt, bool haveBorder, float[] colWidths)
{
try
{
object missing = System.Reflection.Missing.Value; int lenght = doc.Characters.Count - ;
object start = lenght;
object end = lenght; //表格起始坐标
Range tableLocation = doc.Range(ref start, ref end); //添加Word表格
Table table = doc.Tables.Add(tableLocation, dt.Rows.Count + , dt.Columns.Count, ref missing, ref missing);//Word.WdAutoFitBehavior.wdAutoFitContent,Word.WdAutoFitBehavior.wdAutoFitWindow); if (colWidths != null)
{
for (int i = ; i < colWidths.Length; i++)
{
table.Columns[i + ].Width = (float)(28.5F * colWidths[i]);
}
} ///设置TABLE的样式
table.Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast;
table.Rows.Height = app.CentimetersToPoints(float.Parse("0.8"));
table.Range.Font.Size = 10.5F;
table.Range.Font.Name = "宋体";
table.Range.Font.Bold = ;
table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; if (haveBorder == true)
{
//设置外框样式
table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
//样式设置结束
}
for (int i = ; i <= dt.Columns.Count; i++)
{
string colname = dt.Columns[i - ].ColumnName;
table.Cell(, i).Range.Text = colname;
} for (int row = ; row < dt.Rows.Count; row++)
{
for (int col = ; col < dt.Columns.Count; col++)
{
table.Cell(row + , col + ).Range.Text = dt.Rows[row][col].ToString();
}
} return true;
}
catch (Exception e)
{
Console.WriteLine((e.ToString()));
return false;
}
finally
{
}
} public bool InsertTable(System.Data.DataTable dt, bool haveBorder)
{
return InsertTable(dt, haveBorder, null);
} public bool InsertTable(System.Data.DataTable dt)
{
return InsertTable(dt, false, null);
} #endregion 表格操作 #region 查找替换 /// <summary>
/// 获得字符的所在Paragraph的index(耗时过长不建议使用)
/// </summary>
/// <param name="strKey"></param>
/// <returns></returns>
public int FindParagraph(string strKey)
{
int i = ;
Find wfnd;
if (doc.Paragraphs != null && doc.Paragraphs.Count > )
{
for (i = ; i <= doc.Paragraphs.Count; i++)
{
wfnd = doc.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.Text = strKey;
if (wfnd.Execute(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 i;
}
}
}
return -;
} /// <summary>
/// 删除字符的所在段落(耗时过长不建议使用)
/// </summary>
/// <param name="strKeys"></param>
public void DeleteParagraphByKeywords(List<string> strKeys)
{
List<int> indexDeleted = new List<int>(); int i = ;
Find wfnd;
if (doc.Paragraphs != null && doc.Paragraphs.Count > )
{
for (i = ; i <= doc.Paragraphs.Count; i++)
{
wfnd = doc.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
foreach (string strKey in strKeys)
{
wfnd.Text = strKey;
if (wfnd.Execute(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))
{
indexDeleted.Add(i);
}
}
}
}
foreach (int index in indexDeleted.OrderByDescending(x => x).ToList())
{
DeleteParagraph(index);
}
} /// <summary>
/// 删除字符的所在段落
/// </summary>
/// <param name="FindWord"></param>
/// <returns></returns>
public bool DeleteParagraphByKeywords(string FindWord)
{
bool findover = false;
Selection currentselect = app.Selection;//实例化一个selection接口
WdUnits storyUnit = WdUnits.wdStory;
currentselect.HomeKey(storyUnit);
currentselect.Find.ClearFormatting();
currentselect.Find.Text = FindWord;//查询的文字
currentselect.Find.Wrap = WdFindWrap.wdFindStop;//查询完成后停止
findover = currentselect.Find.Execute(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);
WdUnits paraUnit = WdUnits.wdParagraph;
currentselect.Expand(paraUnit);
currentselect.Range.Delete();
return findover;
} /// <summary>
/// 判断文档中是否含有特定字符
/// </summary>
/// <param name="strKey"></param>
/// <returns></returns>
public bool HasWord(string strKey)
{
doc.Content.Find.Text = strKey;
if (doc.Content.Find.Execute(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 true;
}
else
{
return false;
}
} /// <summary>
/// 将特定字符改为黄色
/// </summary>
/// <param name="FindWord"></param>
/// <returns></returns>
public bool MarkWord(string FindWord)
{
bool findover = false;
Selection currentselect = app.Selection;//实例化一个selection接口
currentselect.Find.ClearFormatting();
currentselect.Find.Text = FindWord;//查询的文字
currentselect.Find.Wrap = WdFindWrap.wdFindStop;//查询完成后停止
findover = currentselect.Find.Execute(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);
currentselect.Font.Color = WdColor.wdColorYellow;//设置颜色为黄
return findover;
} /// <summary>
/// 替换文字
/// </summary>
/// <param name="oldText">待替换的文本</param>
/// <param name="newText">替换后的文本</param>
/// <param name="range">范围</param>
/// <returns></returns>
public bool Replace(string oldText, string newText, Range range)
{
object matchCase = false;
object findText = oldText;
object replaceWith = newText;
object wdReplace = WdReplace.wdReplaceOne;
return range.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
ref wdReplace, ref missing, ref missing, ref missing, ref missing);
} /// <summary>
/// 替换
/// </summary>
/// <param name="oldText">待替换的文本</param>
/// <param name="newText">替换后的文本</param>
/// <param name="replaceType">All:替换所有、None:不替换、FirstOne:替换第一个</param>
/// <param name="isCaseSensitive">大小写是否敏感</param>
/// <returns></returns>
public bool Replace(string oldText, string newText, string replaceType, bool isCaseSensitive)
{
if (doc == null)
{
doc = app.ActiveDocument;
}
object findText = oldText;
object replaceWith = newText;
object wdReplace;
object matchCase = isCaseSensitive;
switch (replaceType)
{
case "All":
wdReplace = WdReplace.wdReplaceAll;
break; case "None":
wdReplace = WdReplace.wdReplaceNone;
break; case "FirstOne":
wdReplace = WdReplace.wdReplaceOne;
break; default:
wdReplace = WdReplace.wdReplaceOne;
break;
}
doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置 return doc.Content.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
ref wdReplace, ref missing, ref missing, ref missing, ref missing);
} /// <summary>
/// 替换指定Paragraph中的文本
/// </summary>
/// <param name="oldText"></param>
/// <param name="newText"></param>
/// <param name="replaceType"></param>
/// <param name="isCaseSensitive"></param>
/// <param name="index"></param>
/// <returns></returns>
public bool Replace(string oldText, string newText, string replaceType, bool isCaseSensitive, int index)
{
if (doc == null)
{
doc = app.ActiveDocument;
}
object findText = oldText;
object replaceWith = newText;
object wdReplace;
object matchCase = isCaseSensitive;
switch (replaceType)
{
case "All":
wdReplace = WdReplace.wdReplaceAll;
break; case "None":
wdReplace = WdReplace.wdReplaceNone;
break; case "FirstOne":
wdReplace = WdReplace.wdReplaceOne;
break; default:
wdReplace = WdReplace.wdReplaceOne;
break;
}
doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
return doc.Paragraphs[index].Range.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
ref wdReplace, ref missing, ref missing, ref missing, ref missing);
} #endregion 查找替换 #region 复制粘贴 /// <summary>
/// 复制
/// </summary>
public void Copy()
{
app.Selection.Copy();
} /// <summary>
/// 全选文档
/// </summary>
public void Paste()
{
app.Selection.Paste();
} #endregion 复制粘贴 #region 光标位置 /// <summary>
/// 全选文档
/// </summary>
public void SelectWholeDocument()
{
app.Selection.WholeStory();
} /// <summary>
/// 移动到文档起始位置
/// </summary>
public void MoveToTop()
{
app.Selection.HomeKey(WdUnits.wdStory);
} /// <summary>
/// 移动到文档结束位置
/// </summary>
public void MoveToBottom()
{
app.Selection.EndKey(WdUnits.wdStory);
} /// <summary>
/// 光标移动到指定书签位置,书签不存在时不移动
/// </summary>
/// <param name="bookMarkName"></param>
/// <returns></returns>
public bool GoToBookMark(string bookMarkName)
{
//是否存在书签
if (doc.Bookmarks.Exists(bookMarkName))
{
object what = WdGoToItem.wdGoToBookmark;
object name = bookMarkName;
GoTo(what, missing, missing, name);
return true;
}
return false;
} /// <summary>
/// 移动光标
/// Moves the insertion point to the character position immediately preceding the specified item.
/// </summary>
/// <param name="what">Optional Object. The kind of item to which the selection is moved. Can be one of the WdGoToItem constants.</param>
/// <param name="which">Optional Object. The item to which the selection is moved. Can be one of the WdGoToDirection constants. </param>
/// <param name="count">Optional Object. The number of the item in the document. The default value is 1.</param>
/// <param name="name">Optional Object. If the What argument is wdGoToBookmark, wdGoToComment, wdGoToField, or wdGoToObject, this argument specifies a name.</param>
public void GoTo(object what, object which, object count, object name)
{
app.Selection.GoTo(ref what, ref which, ref count, ref name);
} /// <summary>
/// 光标上移
/// Moves the selection up and returns the number of units it's been moved.
/// </summary>
/// <param name="unit">Optional Object. The unit by which to move the selection. Can be one of the following WdUnits constants: wdLine, wdParagraph, wdWindow or wdScreen etc. The default value is wdLine.</param>
/// <param name="count">Optional Object. The number of units the selection is to be moved. The default value is 1.</param>
/// <param name="extend">Optional Object. Can be either wdMove or wdExtend. If wdMove is used, the selection is collapsed to the end point and moved up. If wdExtend is used, the selection is extended up. The default value is wdMove.</param>
/// <returns></returns>
public void MoveUp(int num = )
{
object unit = WdUnits.wdCharacter;
object count = num;
MoveUp(unit, count, missing);
} /// <summary>
/// 光标上移
/// Moves the selection up and returns the number of units it's been moved.
/// </summary>
/// <param name="unit">Optional Object. The unit by which to move the selection. Can be one of the following WdUnits constants: wdLine, wdParagraph, wdWindow or wdScreen etc. The default value is wdLine.</param>
/// <param name="count">Optional Object. The number of units the selection is to be moved. The default value is 1.</param>
/// <param name="extend">Optional Object. Can be either wdMove or wdExtend. If wdMove is used, the selection is collapsed to the end point and moved up. If wdExtend is used, the selection is extended up. The default value is wdMove.</param>
/// <returns></returns>
public int MoveUp(object unit, object count, object extend)
{
return app.Selection.MoveUp(ref unit, ref count, ref extend);
} /// <summary>
/// 向下移动一个字符
/// </summary>
public void MoveDown()
{
MoveDown();
} /// <summary>
/// 光标下移
/// Moves the selection down and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public void MoveDown(int num = )
{
object unit = WdUnits.wdCharacter;
object count = num;
object extend = WdMovementType.wdMove;
MoveDown(unit, count, extend);
} /// <summary>
/// 光标下移
/// Moves the selection down and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public int MoveDown(object unit, object count, object extend)
{
return app.Selection.MoveDown(ref unit, ref count, ref extend);
} /// <summary>
/// 光标左移
/// Moves the selection to the left and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public void MoveLeft(int num = )
{
object unit = WdUnits.wdCharacter;
object count = num;
MoveLeft(unit, count, missing);
} /// <summary>
/// 光标左移
/// Moves the selection to the left and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public int MoveLeft(object unit, object count, object extend)
{
return app.Selection.MoveLeft(ref unit, ref count, ref extend);
} /// <summary>
/// 向右移动N个字符
/// </summary>
/// <param name="num"></param>
public void MoveRight(int num = )
{
object unit = WdUnits.wdCharacter;
object count = num;
MoveRight(unit, count, missing);
} /// <summary>
/// 光标右移
/// Moves the selection to the left and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public int MoveRight(object unit, object count, object extend)
{
return app.Selection.MoveRight(ref unit, ref count, ref extend);
} #endregion 光标位置 #region 书签操作 public void WriteIntoDocument(string bookmarkName, string context)
{
try
{
object _bookmarkName = bookmarkName;
Bookmark bm = doc.Bookmarks.get_Item(ref _bookmarkName); //返回书签
if (bm != null)
{
bm.Range.Text = context; //设置书签域的内容
}
}
catch (Exception exception)
{
return;
}
} /// <summary>
/// 插入书签
/// 如过存在同名书签,则先删除再插入
/// </summary>
/// <param name="bookMarkName">书签名</param>
public void InsertBookMark(string bookMarkName)
{
//存在则先删除
if (doc.Bookmarks.Exists(bookMarkName))
{
DeleteBookMark(bookMarkName);
}
object range = app.Selection.Range;
doc.Bookmarks.Add(bookMarkName, ref range);
} /// <summary>
/// 删除书签
/// </summary>
/// <param name="bookMarkName">书签名</param>
public void DeleteBookMark(string bookMarkName)
{
if (doc.Bookmarks.Exists(bookMarkName))
{
var bookMarks = doc.Bookmarks;
for (int i = ; i <= bookMarks.Count; i++)
{
object index = i;
var bookMark = bookMarks.get_Item(ref index);
if (bookMark.Name == bookMarkName)
{
bookMark.Delete();
break;
}
}
}
} /// <summary>
/// 删除所有书签
/// </summary>
public void DeleteAllBookMark()
{
for (; doc.Bookmarks.Count > ;)
{
object index = doc.Bookmarks.Count;
var bookmark = doc.Bookmarks.get_Item(ref index);
bookmark.Delete();
}
} /// <summary>
/// 替换书签内容
/// </summary>
/// <param name="bookMarkName">书签名</param>
/// <param name="text">替换后的内容</param>
public void ReplaceBookMark(string bookMarkName, string text)
{
bool isExist = GoToBookMark(bookMarkName);
if (isExist)
{
InsertText(text);
}
} /// <summary>
/// 在书签中插入文本
/// </summary>
/// <param name="sBMName">书签名</param>
/// <param name="sBMValue">文本内容</param>
public void ReplaceBookMarkWithString(string sBMName, string sBMValue)
{
object oBmkName = sBMName;
if (doc.Bookmarks.Exists(sBMName))
{
doc.Bookmarks.get_Item(ref oBmkName).Select();
doc.Bookmarks.get_Item(ref oBmkName).Range.Text = sBMValue;
}
} /// <summary>
/// 在书签中插入图片
/// </summary>
/// <param name="bookmarkName">书签名</param>
/// <param name="imagePath">图片路径</param>
public void ReplaceBookMarkWithImage(string bookmarkName, string imagePath)
{
object oBmkName = bookmarkName; if (doc.Bookmarks.Exists(bookmarkName) && File.Exists(imagePath))
{
object LinkToFile = false;
object SaveWithDocument = true;
doc.Bookmarks.get_Item(ref oBmkName).Select();
app.Selection.InlineShapes.AddPicture(imagePath, ref LinkToFile, ref SaveWithDocument, ref missing);
}
} /// <summary>
/// 在书签中插入指定宽高的图片
/// </summary>
/// <param name="bookmarkName">书签名</param>
/// <param name="imagePath">图片路径</param>
/// <param name="Width">图片宽度</param>
/// <param name="Height">图片高度</param>
public void ReplaceBookMarkWithImage(string bookmarkName, string imagePath, int Width, int Height)
{
object oBmkName = bookmarkName; //读取源图片尺寸
Image picImage = Image.FromFile(imagePath);
int sourcePicWidth = picImage.Width;
int sourcePicHeight = picImage.Height;
double widthHeightRatio = (double)sourcePicWidth / (double)sourcePicHeight;
double heightWidthRatio = (double)sourcePicHeight / (double)sourcePicWidth; //计算插入文档后图片尺寸
int picWidth = Width;
int picHeight = Height; //根据图片原始宽高比得出缩放后的尺寸
if (picWidth > (int)picHeight * widthHeightRatio)
{
picWidth = (int)(picHeight * widthHeightRatio);
}
else
{
picHeight = (int)(picWidth * heightWidthRatio);
} if (doc.Bookmarks.Exists(bookmarkName) && File.Exists(imagePath))
{
object LinkToFile = false;
object SaveWithDocument = true;
doc.Bookmarks.get_Item(ref oBmkName).Select();
InlineShape inlineShape = app.Selection.InlineShapes.AddPicture(imagePath, ref LinkToFile, ref SaveWithDocument, ref missing);
inlineShape.Width = picWidth;
inlineShape.Height = picHeight;
}
} #endregion 书签操作 #region 文件操作 /// <summary>
/// 把Word文档装化为Html文件
/// </summary>
/// <param name="strFileName">要转换的Word文档</param>
/// <param name="strSaveFileName">要生成的具体的Html页面</param>
public bool WordToHtml(string strFileNameForWord, string strSaveFileName)
{
bool result = false;
try
{
Type wordType = app.GetType();
// 打开文件
Type docsType = app.Documents.GetType();
// 转换格式,另存为
Type docType = doc.GetType();
object saveFileName = strSaveFileName;
docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML }); #region 其它格式: ///wdFormatHTML
///wdFormatDocument
///wdFormatDOSText
///wdFormatDOSTextLineBreaks
///wdFormatEncodedText
///wdFormatRTF
///wdFormatTemplate
///wdFormatText
///wdFormatTextLineBreaks
///wdFormatUnicodeText
//-----------------------------------------------------------------------------------
// docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
// null, oDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
// 退出 Word
//wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
// null, oWordApplic, null ); #endregion 其它格式: result = true;
}
catch
{
//throw ( new Exception() );
}
return result;
} /// <summary>
/// 保存当前项目
/// </summary>
public void SaveDocument()
{
if (app == null)
throw new Exception("Create / Open Document first!");
if (doc == null)
throw new Exception("Create / Open Document first!");
if (!doc.Saved)
doc.Save();
} /// <summary>
/// 项目另存为
/// </summary>
public void SaveAsDocument(object path)
{
if (app == null)
throw new Exception("Create / Open Document first!");
if (doc == null)
throw new Exception("Create / Open Document first!");
doc.SaveAs(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);
} /// <summary>
/// 关闭项目
/// </summary>
public void CloseDocument()
{
if (doc != null)
{
try
{
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref doNotSaveChanges, ref missing, ref missing);
}
catch
{
//Already Close
}
}
if (app != null)
{
try
{
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
app.Documents.Close(ref doNotSaveChanges, ref missing, ref missing);
}
catch
{
//Already Close
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
} /// <summary>
/// 退出文档
/// </summary>
public void ExitDocument()
{
if (doc != null)
{
try
{
doc.Close(ref missing, ref missing, ref missing);
}
catch (Exception)
{
throw;
}
} app.Quit();
if (app != null)
{
app = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
} #endregion 文件操作 #region 资源回收 private bool disposed = false; ~WordHelper()
{
//必须为false
Dispose(false);
} public void Dispose()
{
//必须为true
Dispose(true);
//通知垃圾回收机制不再调用终结器(析构器)
GC.SuppressFinalize(this);
} private void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
// 清理托管资源
} if (doc != null)
{
try
{
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref doNotSaveChanges, ref missing, ref missing);
}
catch
{
//Already Close
}
}
if (app != null)
{
try
{
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
app.Documents.Close(ref doNotSaveChanges, ref missing, ref missing);
}
catch
{
//Already Close
}
} //System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
GC.WaitForPendingFinalizers(); //让类型知道自己已经被释放
disposed = true;
} #endregion 资源回收 #region 文档合并 /// <summary>
/// 合并多个Word文档
/// </summary>
/// <param name="docPaths"></param>
/// <param name="output"></param>
public void InsertDocuments(List<string> docPaths, string bookmark)
{
object objIsWordVisible = false;
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
Document outDoc = doc; // 插入到已经打开的文档
foreach (string item in docPaths)
{
object fileName = item;
Document partDoc = app.Documents.Open(
ref fileName, //FileName
ref missing, //ConfirmVersions
ref missing, //ReadOnly
ref missing, //AddToRecentFiles
ref missing, //PasswordDocument
ref missing, //PasswordTemplate
ref missing, //Revert
ref missing, //WritePasswordDocument
ref missing, //WritePasswordTemplate
ref missing, //Format
ref missing, //Enconding
ref objIsWordVisible, //Visible
ref missing, //OpenAndRepair
ref missing, //DocumentDirection
ref missing, //NoEncodingDialog
ref missing //XMLTransform
);
partDoc.Activate();
app.Selection.WholeStory();
app.Selection.Copy(); outDoc.Activate();
GoToBookMark(bookmark);
app.Selection.Paste(); partDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
}
} /// <summary>
/// 合并多个Word文档
/// </summary>
/// <param name="docPaths"></param>
/// <param name="output"></param>
public void MergeDocuments(List<string> docPaths, string output)
{
object objIsWordVisible = false;
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges; object outPath = output;
Document outDoc = app.Documents.Open(
ref outPath, //FileName
ref missing, //ConfirmVersions
ref missing, //ReadOnly
ref missing, //AddToRecentFiles
ref missing, //PasswordDocument
ref missing, //PasswordTemplate
ref missing, //Revert
ref missing, //WritePasswordDocument
ref missing, //WritePasswordTemplate
ref missing, //Format
ref missing, //Enconding
ref objIsWordVisible, //Visible
ref missing, //OpenAndRepair
ref missing, //DocumentDirection
ref missing, //NoEncodingDialog
ref missing //XMLTransform
); foreach (string item in docPaths)
{
object fileName = item;
Document partDoc = app.Documents.Open(
ref fileName, //FileName
ref missing, //ConfirmVersions
ref missing, //ReadOnly
ref missing, //AddToRecentFiles
ref missing, //PasswordDocument
ref missing, //PasswordTemplate
ref missing, //Revert
ref missing, //WritePasswordDocument
ref missing, //WritePasswordTemplate
ref missing, //Format
ref missing, //Enconding
ref objIsWordVisible, //Visible
ref missing, //OpenAndRepair
ref missing, //DocumentDirection
ref missing, //NoEncodingDialog
ref missing //XMLTransform
);
partDoc.Activate();
app.Selection.WholeStory();
app.Selection.Copy(); outDoc.Activate();
MoveToBottom();
app.Selection.Paste(); partDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
} object path = output;
outDoc.SaveAs(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); outDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
} #endregion 文档合并 #region 页面设置 //设置页眉
public void SetHeader(string titleText)
{
app.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
app.Selection.WholeStory();
app.Selection.TypeText(titleText);
app.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;
} //修改页眉 -
public bool ReplacePageHeader(string oldtext, string newtext, int tbcount)
{
try
{
Range range;
for (int i = ; i <= tbcount; i++)
{
range = doc.Sections[i].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
bool sig = range.Find.Execute(oldtext,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
newtext,
WdReplace.wdReplaceAll,
ref missing,
ref missing,
ref missing,
ref missing);
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
} //页面设置
public void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
doc.PageSetup.PageWidth = app.CentimetersToPoints((float)width);
doc.PageSetup.PageHeight = app.CentimetersToPoints((float)height); if (orientation == Orientation.横板)
{
doc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
} doc.PageSetup.TopMargin = (float)(topMargin * );//上边距
doc.PageSetup.LeftMargin = (float)(leftMargin * );//左边距
doc.PageSetup.RightMargin = (float)(rightMargin * );//右边距
doc.PageSetup.BottomMargin = (float)(bottomMargin * );//下边距
} public void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(orientation, , 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
} public void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(Orientation.竖板, , 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
} //插入页脚 -
public bool InsertPageFooter(string text, System.Drawing.Font font, Alignment alignment)
{
try
{
app.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;//页脚
app.Selection.InsertAfter(text);
GetWordFont(app.Selection.Font, font); SetAlignment(app.Selection.Range, alignment); return true;
}
catch (Exception)
{
return false;
}
} public bool InsertPageFooterNumber(System.Drawing.Font font, Alignment alignment)
{
try
{
app.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
app.Selection.WholeStory();
app.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
app.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; app.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;//页脚
app.Selection.TypeText("第"); object page = WdFieldType.wdFieldPage;
app.Selection.Fields.Add(app.Selection.Range, ref page, ref missing, ref missing); app.Selection.TypeText("页/共");
object pages = WdFieldType.wdFieldNumPages; app.Selection.Fields.Add(app.Selection.Range, ref pages, ref missing, ref missing);
app.Selection.TypeText("页"); GetWordFont(app.Selection.Font, font);
SetAlignment(app.Selection.Range, alignment);
app.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
return true;
}
catch (Exception)
{
return false;
}
} //修改页脚
public bool ReplacePageFooter(string oldtext, string newtext, int tbcount)
{
try
{
Range range;
for (int i = ; i <= tbcount; i++)
{
range = doc.Sections[i].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
bool sig = range.Find.Execute(oldtext,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
newtext,
WdReplace.wdReplaceAll,
ref missing,
ref missing,
ref missing,
ref missing);
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
} #endregion 页面设置 #region 常用方法 /// <summary>
/// 给表头排序
/// </summary>
/// <param name="tableNo"></param>
/// <param name="no"></param>
/// <returns></returns>
public bool TableTitleNumberOrder(string tableNo, int no)
{
bool findover = false;
Selection currentselect = app.Selection;//实例化一个selection接口
currentselect.Find.ClearFormatting();
currentselect.Find.Text = tableNo;//查询的文字
currentselect.Find.Wrap = WdFindWrap.wdFindStop;//查询完成后停止
findover = currentselect.Find.Execute(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); currentselect.Expand(WdUnits.wdParagraph); //扩展选区到整行
string oldWord = Regex.Match(currentselect.Range.Text, tableNo + @"\.\d+", RegexOptions.IgnoreCase).Value;
string newWord = tableNo + "." + no.ToString();
Replace(oldWord, newWord, currentselect.Range);
currentselect.MoveDown(WdUnits.wdParagraph, );
return findover;
} //获取Word中的颜色 -
public WdColor GetWordColor(Color c)
{
UInt32 R = 0x1, G = 0x100, B = 0x10000;
return (WdColor)(R * c.R + G * c.G + B * c.B);
} #endregion 常用方法 public enum Orientation
{
横板,
竖板
} public enum Alignment
{
左对齐,
居中,
右对齐
}
}
}
【小丸类库系列】Word操作类的更多相关文章
- 【小丸类库系列】Excel操作类
using Microsoft.Office.Interop.Excel; using System; using System.IO; using System.Reflection; namesp ...
- C#常用操作类库三(XML操作类)
/// <summary> /// XmlHelper 的摘要说明. /// xml操作类 /// </summary> public class XmlHelper { pr ...
- Java面向对象_常用类库api——日期操作类
Data类 类Data表示特定的瞬间,精确到毫秒,也就是程序运行时的当前时间 Data data=new Data();//实例化Data对象,表示当前时间 Calendar类 日历类,使用此类可以将 ...
- 【个人使用.Net类库】(3)Excel文件操作类(基于NPOI)
Web开发工作中经常要根据业务的需要生成对应的报表.经常采用的方法如下: 将DataTable导出至Excel文件; 读取模板Excel文件; 修改模板Excel文件对应的内容. 因此,便想到封装一个 ...
- DocX开源WORD操作组件的学习系列四
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- DocX开源WORD操作组件的学习系列三
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- DocX开源WORD操作组件的学习系列二
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- DocX开源WORD操作组件的学习系列一
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- c/c++ 模板与STL小例子系列<二> 模板类与友元函数
c/c++ 模板与STL小例子系列 模板类与友元函数 比如某个类是个模板类D,有个需求是需要重载D的operator<<函数,这时就需要用到友元. 实现这样的友元需要3个必要步骤 1,在模 ...
随机推荐
- 转载Sql 获取数据库所有表及其字段名称,类型,长度
转载原地址 http://www.cnblogs.com/Fooo/archive/2009/08/27/1554769.html SELECT (case when a.colorder=1 the ...
- MFRCC522 SPI无法通讯【worldsing笔记】
用单片机于MRFC522与单片接时,加上485通讯后出现很诡异的像: 只要485芯片上有收到外部发送的信号时RC522就死掉,经过仿真卡在了SPI的收发部分(等待回复) u8 MFRC522Write ...
- 【WIN32进阶之路】:线程同步技术纲要
前面博客讲了互斥量(MUTEX)和关键段(CRITICAL SECTION)的使用,想来总觉不妥,就如盲人摸象一般,窥其一脚而言象,难免以偏概全,追加一篇博客查遗补漏. win32下的线程同步技术分为 ...
- 【转】Netty那点事(四)Netty与Reactor模式
[原文]https://github.com/code4craft/netty-learning/blob/master/posts/ch4-reactor.md 一:Netty.NIO.多线程? 时 ...
- Ubuntu 安装 Courier New字体
apt-get install ttf-mscorefonts-installer 它的本质是安装 Courier New字体 安装的时候会出现一个协议 按TAB键 ,可以选中<确定>按 ...
- Codeforces Round #321 (Div. 2) A. Kefa and First Steps 水题
A. Kefa and First Steps Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/58 ...
- URL是否有效
unit Unit1;interfaceuses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Syste ...
- 《Java并发编程实战》第十五章 原子变量与非堵塞同步机制 读书笔记
一.锁的劣势 锁定后假设未释放.再次请求锁时会造成堵塞.多线程调度通常遇到堵塞会进行上下文切换,造成很多其它的开销. 在挂起与恢复线程等过程中存在着非常大的开销,而且通常存在着较长时间的中断. 锁可能 ...
- Android选择系统相册或拍照上传
PhotoUtils.rar
- careercup-C和C++ 13.3
13.3 C++中的虚函数是如何工作的? 解答 虚函数依赖虚函数表进行工作.如果一个类中,有函数被关键词virtual进行修饰, 那么一个虚函数表就会被构建起来保存这个类中虚函数的地址.同时, 编译器 ...