本文整理汇总了C#中Microsoft.Office.Interop.Word.Application类的典型用法代码示例。如果您正苦于以下问题:C# Application类的具体用法?C# Application怎么用?C# Application使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Application类属于Microsoft.Office.Interop.Word命名空间,在下文中一共展示了Application类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: WordToPDF
public static bool WordToPDF(string sourcePath, string targetPath)
{
bool result = false;
Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
Microsoft.Office.Interop.Word.Application application = null;
Microsoft.Office.Interop.Word.Document document = null;
object unknow = System.Type.Missing;
application = new Microsoft.Office.Interop.Word.Application();
application.Visible = false;
document = application.Documents.Open(sourcePath);
document.SaveAs();
document.ExportAsFixedFormat(targetPath, exportFormat, false);
//document.ExportAsFixedFormat(targetPath, exportFormat);
result = true;
//application.Documents.Close(ref unknow, ref unknow, ref unknow);
document.Close(ref unknow, ref unknow, ref unknow);
document = null;
application.Quit();
//application.Quit(ref unknow, ref unknow, ref unknow);
application = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return result;
}
开发者ID:caengcjd,项目名称:reslove_word,代码行数:30,代码来源:Util.cs
示例2: Convert
public byte[] Convert()
{
var objWord = new Application();
if (File.Exists(FileToSave))
{
File.Delete(FileToSave);
}
try
{
objWord.Documents.Open(FileName: FullFilePath);
objWord.Visible = false;
if (objWord.Documents.Count > 0)
{
var oDoc = objWord.ActiveDocument;
oDoc.SaveAs(FileName: FileToSave, FileFormat: WdSaveFormat.wdFormatHTML);
oDoc.Close(SaveChanges: false);
}
}
finally
{
objWord.Application.Quit(SaveChanges: false);
}
return base.ReadConvertedFile();
}
开发者ID:raovat,项目名称:develop,代码行数:25,代码来源:DocToHtml.cs
示例3: Main
static void Main(string[] args)
{
try
{
FileInfo file = new FileInfo(@args[0]);
if (file.Extension.ToLower() == ".doc" || file.Extension.ToLower() == ".xml" || file.Extension.ToLower() == ".wml")
{
Word._Application application = new Word.Application();
object fileformat = Word.WdSaveFormat.wdFormatXMLDocument;
object filename = file.FullName;
object newfilename = Path.ChangeExtension(file.FullName, ".docx");
Word._Document document = application.Documents.Open(filename);
document.Convert();
document.SaveAs(newfilename, fileformat);
document.Close();
document = null;
application.Quit();
application = null;
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Missing parameter: IndexOutOfRangeException {0}", e);
}
}
开发者ID:Jeeeeeiel,项目名称:doc2docx,代码行数:29,代码来源:Program.cs
示例4: Print2
public static void Print2(string wordfile, string printer = null)
{
oWord.Application wordApp = new oWord.Application();
wordApp.Visible = false;
wordApp.Documents.Open(wordfile);
wordApp.DisplayAlerts = oWord.WdAlertLevel.wdAlertsNone;
System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();
if (printer == null) // print to all installed printers
{
foreach (string p in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
try
{
settings.PrinterName = p;
wordApp.ActiveDocument.PrintOut(false);
}
catch (Exception ex)
{
Logger.LogException(ex, true);
}
}
}
else
{
settings.PrinterName = printer;
wordApp.ActiveDocument.PrintOut(false);
}
wordApp.Quit(oWord.WdSaveOptions.wdDoNotSaveChanges);
}
开发者ID:nblaurenciana-md,项目名称:Websites,代码行数:33,代码来源:WordDocServerSidePrinter.cs
示例5: Main
static void Main(string[] args)
{
var checkAccounts = new List<Account> {
new Account {
ID = 345,
Balance = 541.27
},
new Account {
ID = 123,
Balance = -127.44
}
};
DisplayInExcel(checkAccounts, (account, cell) =>
{
//Multiline lambda
cell.Value2 = account.ID;
cell.get_Offset(0, 1).Value2 = account.Balance;
if (account.Balance < 0)
{
cell.Interior.Color = 255;
cell.get_Offset(0, 1).Interior.Color = 255;
}
});
var word = new Word.Application();
word.Visible = true;
word.Documents.Add();
word.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);
}
开发者ID:julid29,项目名称:confsamples,代码行数:31,代码来源:Program.cs
示例6: CompareInWord
public static void CompareInWord(string fullpath, string newFullpath, string saveName, string saveDir, string author, bool save = false) {
Object missing = Type.Missing;
try {
var wordapp = new Microsoft.Office.Interop.Word.Application();
try {
var doc = wordapp.Documents.Open(fullpath, ReadOnly: true);
doc.Compare(newFullpath, author ?? missing);
doc.Close(WdSaveOptions.wdDoNotSaveChanges); // Close the original document
var dialog = wordapp.Dialogs[WdWordDialog.wdDialogFileSummaryInfo];
// Pre-set the save destination by setting the Title in the save dialog.
// This must be done through reflection, since "dynamic" is only supported in .NET 4
dialog.GetType().InvokeMember("Title", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
null, dialog, new object[] {saveName});
dialog.Execute();
wordapp.ChangeFileOpenDirectory(saveDir);
if (!save) {
wordapp.ActiveDocument.Saved = true;
}
wordapp.Visible = true;
wordapp.Activate();
// Simple hack to bring the window to the front.
wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMinimize;
wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMaximize;
} catch (Exception ex) {
Logger.LogException(ex);
ShowMessageBox("Word could not open these documents. Please edit the file manually.", "Error");
wordapp.Quit();
}
} catch (Exception ex) {
Logger.LogException(ex);
ShowMessageBox("Could not start Microsoft Word. Office 2003 or higher is required.", "Could not start Word");
}
}
开发者ID:SciGit,项目名称:scigit-client,代码行数:35,代码来源:Util.cs
示例7: PasteTest
public void PasteTest()
{
var fileName = TestFileNames.SourceFile;
var word = new Application { Visible = false };
var doc = word.Documents.Open(fileName);
try
{
// ReSharper disable UseIndexedProperty
var range = doc.Bookmarks.get_Item("Bibliography").Range;
// ReSharper restore UseIndexedProperty
var html = Utils.GetHtmlClipboardText("Hello <i>World!</i>");
Clipboard.SetText(html, TextDataFormat.Html);
range.PasteSpecial(DataType: WdPasteDataType.wdPasteHTML);
var destFileName = Path.Combine(Path.GetDirectoryName(fileName),
Path.GetFileNameWithoutExtension(fileName) + "-updated" + Path.GetExtension(fileName));
word.ActiveDocument.SaveAs(destFileName);
}
catch (Exception ex)
{
Debug.WriteLine(ex.GetMessage());
}
finally
{
word.Quit(false);
}
}
开发者ID:dreikanter,项目名称:refrep,代码行数:29,代码来源:PasteHtmlTest.cs
示例8: abstarctRichBoxString
private string abstarctRichBoxString(string keyWord, Application testWord)//暂定private testDoc提取richBox内容
{
testWord.Selection.Find.Text = keyWord;//查询的文字
string s = "";
string previous = "";
string now = "";
Selection
currentSelect = testWord.Selection;
WdInformation pageNum = WdInformation.wdActiveEndAdjustedPageNumber;
WdInformation rowNum = WdInformation.wdFirstCharacterLineNumber;
while (testWord.Selection.Find.Execute())
{
object page = currentSelect.get_Information(pageNum);
object row = currentSelect.get_Information(rowNum);
previous = now;
now = currentSelect.Paragraphs[1].Range.Text.Trim();
list.Add(page);
list.Add(row);
if (!now.Equals(previous))
s += page + "页" + row + "行 " + now + "\r\r";
}
testWord.Selection.HomeKey(WdUnits.wdStory, Type.Missing);
return s;
}
开发者ID:v02zk,项目名称:Mycoding,代码行数:25,代码来源:keyWord.cs
示例9: WordDocument
public WordDocument(String templateName, bool visible)
{
List<int> startedWords = new List<int>();
foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
{
startedWords.Add(p.Id);
}
Object missingValue = Missing.Value;
Object template = templateName;
if (wordapp == null)
wordapp = new Word.Application();
foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
{
if (!startedWords.Contains(p.Id))
{
IDs.Add(p.Id);
}
}
wordapp.Visible = visible;
doc = wordapp.Documents.Add(ref template,
ref missingValue, ref missingValue, ref missingValue);
doc.ActiveWindow.Selection.MoveEnd(Word.WdUnits.wdStory);
tempFileName = Path.Combine(Path.GetDirectoryName(templateName), tempFileName);
}
开发者ID:Tinkris,项目名称:TeemTest,代码行数:28,代码来源:WordDocument.cs
示例10: Convert
public override void Convert(String inputFile, String outputFile)
{
Object nothing = System.Reflection.Missing.Value;
try
{
if (!File.Exists(inputFile))
{
throw new ConvertException("File not Exists");
}
if (IsPasswordProtected(inputFile))
{
throw new ConvertException("Password Exist");
}
app = new Word.Application();
docs = app.Documents;
doc = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing);
doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing);
}
catch (Exception e)
{
release();
throw new ConvertException(e.Message);
}
release();
}
开发者ID:teambition,项目名称:OfficeConverter,代码行数:27,代码来源:WordConverter.cs
示例11: With
// Usage:
// using Word = Microsoft.Office.Interop.Word;
// Action<Word.Application> f = w =>
// {
// var d = w.Documents.Open(@"C:\Foo.docx");
// };
// Word1.With(f);
internal static void With(Action<Word.Application> f)
{
Word.Application app = null;
try
{
app = new Word.Application
{
DisplayAlerts = Word.WdAlertLevel.wdAlertsNone,
Visible = true
};
f(app);
}
finally
{
if (app != null)
{
if (0 < app.Documents.Count)
{
// Unlike Excel, Close(...) makes an error when app.Documents.Count == 0
// Unlike Excel, Close(...) without wdDoNotSaveChanges shows a prompt for a dirty document.
app.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
app.Quit();
// Both of the following are needed in some cases
// while none of them are needed in other cases.
Marshal.FinalReleaseComObject(app);
GC.Collect();
}
}
}
开发者ID:tatsuya,项目名称:csharp-utility-library,代码行数:40,代码来源:Word1.cs
示例12: SaveWordDoc
public static void SaveWordDoc(string originFile, IEnumerable<KeyValuePair<string, string>> replaceList = null, string targetFile = null, WdSaveFormat format = WdSaveFormat.wdFormatDocumentDefault, MsoEncoding encoding = MsoEncoding.msoEncodingAutoDetect)
{
Word.Application ap = null;
Word.Document doc = null;
object missing = Type.Missing;
bool success = true;
replaceList = replaceList ?? new Dictionary<string, string>();
targetFile = targetFile ?? originFile;
if(targetFile.LastIndexOf('.')>targetFile.LastIndexOf('/')||targetFile.LastIndexOf('.')>targetFile.LastIndexOf('\\'))
targetFile=targetFile.Remove(targetFile.LastIndexOf('.'));
try
{
ap = new Word.Application();
ap.DisplayAlerts = WdAlertLevel.wdAlertsNone;
doc = ap.Documents.Open(originFile, ReadOnly: false, Visible: false);
doc.Activate();
Selection sel = ap.Selection;
if (sel == null)
throw new Exception("Unable to acquire Selection...no writing to document done..");
switch (sel.Type)
{
case WdSelectionType.wdSelectionIP:
replaceList.ToList().ForEach(p => sel.Find.Execute(FindText: p.Key, ReplaceWith: p.Value, Replace: WdReplace.wdReplaceAll));
break;
default:
throw new Exception("Selection type not handled; no writing done");
}
sel.Paragraphs.LineUnitAfter = 0;
sel.Paragraphs.LineUnitBefore = 0;
sel.Paragraphs.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle;
doc.SaveSubsetFonts = false;
doc.SaveAs(targetFile, format, Encoding: encoding);
}
catch (Exception)
{
success = false;
}
finally
{
if (doc != null)
{
doc.Close(ref missing, ref missing, ref missing);
Marshal.ReleaseComObject(doc);
}
if (ap != null)
{
ap.Quit(ref missing, ref missing, ref missing);
Marshal.ReleaseComObject(ap);
}
if(!success)
throw new Exception(); // Could be that the document is already open (/) or Word is in Memory(?)
}
}
开发者ID:claudioalpereira,项目名称:Superaid,代码行数:60,代码来源:MyOffice.cs
示例13: A
public A()
{
oracon = new OracleConnection("server = 127.0.0.1/orcx; user id = qzdata; password = xie51");
oracon2 = new OracleConnection("server = 10.5.67.11/pdbqz; user id = qzdata; password = qz9401tw");
wordapp = new word.Application();
worddoc = new word.Document();
worddoc = wordapp.Documents.Add();
worddoc.SpellingChecked = false;
worddoc.ShowSpellingErrors = false;
// wordapp.Visible = true;
ta.wordapp = wordapp;
ta.worddoc = worddoc;
if (IS_YEAR)
{
datestr = dsf.GetDateStr(the_year_begin_int, the_month_begin_int, the_year_end_int, the_month_end_int);
}
else
{
datestr = dsf.GetDateStr(the_date);
}
// datestr_abid = "(" + datestr + "and a.ab_id >=1 and a.ab_id <= 7)";
datestr_abid = "(" + datestr + "and" + abidstr + ")";
oracon2.Open();
orahlper = new OraHelper(oracon2);
orahlper.feedback = true;
the_month_begin = new DateTime(the_date.Year, the_date.Month, 1, 0, 0, 0);
the_month_end = the_month_begin.AddMonths(1).AddSeconds(-1);
}
开发者ID:xiexi1990,项目名称:ReportGen,代码行数:33,代码来源:Program.cs
示例14: MainWin
public MainWin()
{
oWord = new Word.Application();
oWord.Visible = true;
InitializeComponent();
}
开发者ID:kamwoods,项目名称:FontAnalysis,代码行数:7,代码来源:MainWin.cs
示例15: button1_Click
private void button1_Click(object sender, EventArgs e)
{
//закриває всі відкриті ворди
String[] s = textBox1.Text.Split(new[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
int step = (int) 100/s.Length;
for (int i = 0; i < s.Length; i++)
{
try
{
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
var wordDocument = appWord.Documents.Open(s[i]);
s[i] = s[i].Replace(".docx", ".pdf");
s[i] = s[i].Replace(".doc", ".pdf");
wordDocument.ExportAsFixedFormat(s[i], WdExportFormat.wdExportFormatPDF);
wordDocument.Close();
appWord.Quit();
}
catch{}
progressBar1.Value += step;
}
progressBar1.Value = 100;
MessageBox.Show("Готово", "Звіт про виконання", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
progressBar1.Value = 0;
}
开发者ID:AndreFG,项目名称:Utilits,代码行数:25,代码来源:MainForm.cs
示例16: setup
public void setup()
{
wordApp = WordApplicationHelper.GetApplication();
if (wordApp.Documents.Exists(IOHelpers.FirmAddressTestData))
wordApp.Documents.First(IOHelpers.FirmAddressTestData).Close(Wd.WdSaveOptions.wdDoNotSaveChanges);
doc = wordApp.Documents.Open(IOHelpers.FirmAddressTestData.FullName);
}
开发者ID:beachandbytes,项目名称:GorillaDocs,代码行数:7,代码来源:FirmAddressTests.cs
示例17: PrepareApplication
void PrepareApplication()
{
if (_application == null)
{
_application = new Microsoft.Office.Interop.Word.Application { Caption = WordApplicationTitle, Visible = true };
((ApplicationEvents4_Event)_application).Quit += _application_ApplicationEvents4_Event_Quit;
var processId = Win32Helper.GetProcessIdByWindowTitle(WordApplicationTitle);
//var processId = Win32Helper.GetEmtyWordProcess();
while (processId < 0)
{
Thread.Sleep(5);
processId = Win32Helper.GetProcessIdByWindowTitle(WordApplicationTitle);
//processId = Win32Helper.GetEmtyWordProcess();
}
_application.Visible = false;
HostedHandle = Win32Helper.FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, WordApplicationTitle).ToInt32();
_application.Visible = true;
}
}
开发者ID:herohut,项目名称:elab,代码行数:27,代码来源:MsWordControl.cs
示例18: Main
static void Main(string[] args)
{
FileInfo file = new FileInfo(@args[0]);
if (file.Extension.ToLower() == ".docx")
{
Console.WriteLine("Starting file name extraction...");
//Set the Word Application Window Title
string wordAppId = "" + DateTime.Now.Ticks;
Word.Application word = new Word.Application();
word.Application.Caption = wordAppId;
word.Application.Visible = true;
int processId = GetProcessIdByWindowTitle(wordAppId);
word.Application.Visible = false;
try
{
object filename = file.FullName;
Word._Document document = word.Documents.OpenNoRepairDialog(filename);
Console.WriteLine("Extracting file names from document '{0}'.", file);
//Console.WriteLine("Document has {0} shapes.", document.InlineShapes.Count);
if (document.InlineShapes.Count > 0)
{
foreach (Word.InlineShape shape in document.InlineShapes)
{
if (shape.Type == Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject)
{
Console.WriteLine("Found file name: {0}", shape.OLEFormat.IconLabel);
}
}
}
document.Close();
document = null;
word.Quit();
word = null;
Console.WriteLine("Success, quitting Word.");
}
catch (Exception e)
{
Console.WriteLine("Error ocurred: {0}", e);
}
finally
{
// Terminate Winword instance by PID.
Console.WriteLine("Terminating Winword process with the Windowtitle '{0}' and the Application ID: '{1}'.", wordAppId, processId);
Process process = Process.GetProcessById(processId);
process.Kill();
}
}
else
{
Console.WriteLine("Only DOCX files possible.");
}
}
开发者ID:Softcom,项目名称:FileNameExtractor,代码行数:59,代码来源:Program.cs
示例19: btn_OutPut_Click
private void btn_OutPut_Click(object sender, EventArgs e)
{
List<Fruit> P_Fruit = new List<Fruit>();//创建数据集合
foreach (DataGridViewRow dgvr in dgv_Message.Rows)
{
P_Fruit.Add(new Fruit()//向数据集合添加数据
{
Name = dgvr.Cells[0].Value.ToString(),
Price = Convert.ToSingle(dgvr.Cells[1].Value.ToString())
});
}
SaveFileDialog P_SaveFileDialog =//创建保存文件对话框对象
new SaveFileDialog();
P_SaveFileDialog.Filter = "*.doc|*.doc";
if (DialogResult.OK ==//确认是否保存文件
P_SaveFileDialog.ShowDialog())
{
ThreadPool.QueueUserWorkItem(//开始线程池
(pp) =>//使用lambda表达式
{
G_wa = new Microsoft.Office.Interop.Word.Application();//创建应用程序对象
object P_obj = "Normal.dot";//定义文档模板
Word.Document P_wd = G_wa.Documents.Add(//向Word应用程序中添加文档
ref P_obj, ref G_missing, ref G_missing, ref G_missing);
Word.Range P_Range = P_wd.Range(//得到文档范围
ref G_missing, ref G_missing);
object o1 = Word.WdDefaultTableBehavior.//设置文档中表格格式
wdWord8TableBehavior;
object o2 = Word.WdAutoFitBehavior.//设置文档中表格格式
wdAutoFitWindow;
Word.Table P_WordTable = P_Range.Tables.Add(P_Range,//在文档中添加表格
P_Fruit.Count ,2, ref o1, ref o2);
P_WordTable.Cell(1, 1).Range.Text = "水果";//向表格中添加信息
P_WordTable.Cell(1, 2).Range.Text = "价格";//向表格中添加信息
for (int i = 2; i < P_Fruit.Count + 1; i++)
{
P_WordTable.Cell(i, 1).Range.Text =//向表格中添加信息
P_Fruit[i - 2].Name;
P_WordTable.Cell(i, 2).Range.Text =//向表格中添加信息
P_Fruit[i - 2].Price.ToString();
}
object P_Path = P_SaveFileDialog.FileName;
P_wd.SaveAs(//保存Word文件
ref P_Path,
ref G_missing, ref G_missing, ref G_missing, ref G_missing,
ref G_missing, ref G_missing, ref G_missing, ref G_missing,
ref G_missing, ref G_missing, ref G_missing, ref G_missing,
ref G_missing, ref G_missing, ref G_missing);
((Word._Application)G_wa.Application).Quit(//退出应用程序
ref G_missing, ref G_missing, ref G_missing);
this.Invoke(//调用窗体线程
(MethodInvoker)(() =>//使用lambda表达式
{
MessageBox.Show(//弹出消息对话框
"成功创建Word文档!", "提示!");
}));
});
}
}
开发者ID:TGHGH,项目名称:C-1200,代码行数:59,代码来源:Frm_Main.cs
示例20: CreateXWordMenu
/// <summary>
/// Creates the XWord menu.
/// </summary>
/// <param name="wordApplication">The <code>Word.Application</code>.</param>
public void CreateXWordMenu(Word.Application wordApplication)
{
this.application = wordApplication;
this.officeMenuBar = wordApplication.CommandBars.ActiveMenuBar;
BuildMenus();
EnqueueEventHandlers();
DisableXWordMenus();
}
开发者ID:polx,项目名称:sandbox,代码行数:12,代码来源:MenuManager.cs
注:本文中的Microsoft.Office.Interop.Word.Application类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论