最近有需求要匯出Word檔案,
因為之前沒有相關經驗,
有找到使用Microsoft Word 11.0 Object library的範例,
但是卻一直在SaveAs的地方一直打開存檔的Dialog,
執行到第二次就發生錯誤,
(應該說以下程式,我按一次Button後,它會無限次數打開Dialog,不知道為什麼)
不知道到底是甚麼原因,
是不是這個範例有問題,
可是找了好幾個範例都是這樣寫,
可以麻煩知道的大大回答一下嗎?
感恩~
SaveFileDialog sf = new SaveFileDialog();//使用存檔的對話框
sf.DefaultExt = "doc";
sf.Filter = "Word 97-2003 文件 (*.doc)|*.doc";
sf.AddExtension = true;
sf.RestoreDirectory = false;
sf.Title = "另存新檔";
sf.InitialDirectory = @"C:/";
Word._Application word_app = new Microsoft.Office.Interop.Word.Application();
Word._Document word_document;
object path;//設定一些object宣告
object oMissing = System.Reflection.Missing.Value;
object oSaveChanges = Word.WdSaveOptions.wdSaveChanges;
object oformat = Word.WdSaveFormat.wdFormatDocument;//wdFormatDocument97為Word 97-2003 文件 (*.doc)
object start = 0, end = 0;
if (word_app == null)//若無office程式則無法使用
MessageBox.Show("無法建立word檔案!!");
else
{
if (sf.ShowDialog() == DialogResult.OK)
{
path = sf.FileName;
word_app.Visible = false;//不顯示word程式
word_app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;//不顯示警告或彈跳視窗。如果出現彈跳視窗,將選擇預設值繼續執行。
word_document = word_app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);//新增檔案
Word.Range rng = word_document.Range(ref start, ref end);
Word.Table table = word_document.Tables.Add(rng, 10, 6, ref oMissing, ref oMissing);//設定表格
table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;//內框線
table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;//外框線
table.Select();//選取指令
word_app.Selection.Font.Name = "標楷體";//設定選取的資料字型
word_app.Selection.Font.Size = 10;//設定文字大小
word_app.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //將其設為靠中間
for (int i = 1; i <= 10; i++)//將表格的資料寫入word檔案裡,第一列的值為1,第一行的值為1
{
for (int j = 1; j <= 6; j++)
{
table.Cell(i, j).Range.Text = i + "," + j;
table.Cell(i, j).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
table.Columns[j].Width = 70f;
table.Rows[i].Height = 70f;
}
}
word_document.SaveAs(ref path, ref oformat, 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);//存檔
word_document.Close(ref oFalse, ref oMissing, ref oMissing);//關閉
System.Runtime.InteropServices.Marshal.ReleaseComObject(word_document);//釋放
word_document = null;
word_app.Quit(ref oMissing, ref oformat, ref oMissing);//結束
System.Runtime.InteropServices.Marshal.ReleaseComObject(word_app);//釋放
word_app = null;
}
sf.Dispose();//釋放
sf = null;
}