首先建立DOC模板
再次,在項目中相關頁面添加此重點方法
重點方法:
private string PrintWord() { try { string templatePath = _SaveDocPath + "/Template/RPMB.doc"; //產生的文檔路徑 filePath = _SaveDocPath + "/HZM/"; if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); if (!File.Exists(templatePath)) return "error:伺服器沒有模版"; filePath = filePath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc"; //copy一份 File.Copy(templatePath, filePath, true); object oMissing = System.Reflection.Missing.Value; app = new Word.Application(); app.Visible = false; object fileName = filePath; doc = app.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); if (doc == null) { return "error:伺服器沒有開啟Word"; } //判斷書籤 //加入doc書籤的方法 if (doc.Bookmarks.Exists("KJJBJNF")) { doc.Bookmarks["KJJBJNF"].Range.Text = DateTime.Now.ToString("yyyyMMddHHmmss").ToString() + "標題"; } Word.Tables tabs1 = doc.Tables; if (tabs1 != null && tabs1.Count > 0) { Word.Table dt_Word = tabs1[1]; string strsql = "select * from stuInfo"; DataTable dt_Stu = RunSQLReturnTable(strsql); //預設從第2行開始,第1行為模板中的標題 int rowIdex = 2; foreach (DataRow row in dt_Stu.Rows) { object miss = System.Reflection.Missing.Value; dt_Word.Rows.Add(miss); //將從資料庫中查詢的資料,此處進行迴圈載入即可 //1 .向儲存格中添加資料 dt_Word.Cell(rowIdex, 1).Range.Text = row["No"].ToString(); //2. 設定該儲存格中字型的對齊 dt_Word.Cell(rowIdex, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; dt_Word.Cell(rowIdex, 2).Range.Text = row["Name"].ToString(); dt_Word.Cell(rowIdex, 3).Range.Text = row["Sex"].ToString(); dt_Word.Cell(rowIdex, 4).Range.Text = row["Age"].ToString(); // 3 .合併儲存格Merge(行,列) //dt_Word.Cell(rowIdex, 3).Merge(dt_Word.Cell(rowIdex, 4)); rowIdex++; } } doc.Save(); QuitWord(); } catch (Exception ex) { QuitWord(); return "error:" + ex.Message; } return "true"; }
3.匯出即可。
附加源碼 http://download.csdn.net/detail/hugaozhuang/6652495