本文整理汇总了C#中Microsoft.Office.Interop.Word.Application类的典型用法代码示例。如果您正苦于以下问题:C# Application类的具体用法?C# Application怎么用?C# Application使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Application类属于Microsoft.Office.Interop.Word命名空间,在下文中一共展示了Application类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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();
}
示例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);
}
}
示例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);
}
示例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);
}
示例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");
}
}
示例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);
}
}
示例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;
}
示例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);
}
示例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();
}
示例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();
}
}
}
示例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(?)
}
}
示例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);
}
示例14: MainWin
public MainWin()
{
oWord = new Word.Application();
oWord.Visible = true;
InitializeComponent();
}
示例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;
}