private void f_ReadWordContent(string strPathFile) { Word.ApplicationClass wordApp = new ApplicationClass(); object file = @strPathFile; object o_true = true; object nullobj = System.Reflection.Missing.Value; Word.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref o_true, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj); string strFile2Html = ""; strFile2Html = strPathFile.Replace(".html", ".doc"); object o_newfilename = strFile2Html; object o_format = Word.WdSaveFormat.wdFormatDocument; object o_encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8; object o_endings = Word.WdLineEndingType.wdCRLF; // SaveAs requires lots of parameters, but we can leave most of them empty: wordApp.ActiveDocument.SaveAs(ref o_newfilename, ref o_format, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref o_encoding, ref nullobj, ref nullobj, ref o_endings, ref nullobj); //------- doc.Close(ref nullobj, ref nullobj, ref nullobj); wordApp.Quit(ref nullobj, ref nullobj, ref nullobj); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); }
void dayReport(DateTime dates) { try { //if (dates.Year == DateTime.Now.Year && dates.Month == DateTime.Now.Month && dates.Day == DateTime.Now.Day) //{ // MessageBox.Show("只能选择今天之前的日期查看"); // return; //} string date = Form1.str + "//日报表" + dates.ToShortDateString() + ".doc"; File.Copy(Form1.str + "//day.doc", date, true); this.axFramerControl1.Open(date); this.axFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileSave, false); this.axFramerControl1.Toolbars = false; this.axFramerControl1.Titlebar = false; //写保护,只能读取 Object myObj = this.axFramerControl1.ActiveDocument; if (myObj == null) { return; } Word.Document wdoc = (Word.Document)myObj; Word.Application ThisApplication = wdoc.Application; object missing = Type.Missing; //wdoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref missing, ref missing, ref missing, ref missing); FillCommonTable(wdoc, _dat_day.Value, "d"); } catch (Exception ex) { MessageBox.Show("创建日报表出错!" + ex.Message); } }
public void SaveAsHtml(Word.Document oDoc, string strFileName) { object fileName = strFileName; //wdFormatWebArchive保存为单个网页文件 //wdFormatFilteredHTML保存为过滤掉word标签的htm文件,缺点是有图片的话会产生网页文件夹 if (File.Exists(strFileName)) { if (MessageBox.Show("文件'" + strFileName + "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK) { object Format = (int)Word.WdSaveFormat.wdFormatWebArchive; oDoc.SaveAs(ref fileName, ref Format, 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); } else { Clipboard.Clear(); } } else { object Format = (int)Word.WdSaveFormat.wdFormatWebArchive; oDoc.SaveAs(ref fileName, ref Format, 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> /// catches Word's close event /// starts a Thread that send a ESC to the word window ;) /// </summary> /// <param name="doc"></param> /// <param name="test"></param> private void OnClose(Word.Document doc, ref bool cancel) { if (!deactivateevents) { cancel = true; } ////////saveDoc(wDoc); }
/// <summary> /// Sets all internal state back to null /// </summary> private void ResetState() { m_wordApp = null; m_wordDoc = null; m_originalFileName = null; m_newFileName = null; m_newFormatType = null; m_handleTrackedChanges = false; m_statusFileName = null; }
//public void closeDoc() //{ // object missing = System.Reflection.Missing.Value; // //document.Save(); // document.Close(ref missing, ref missing, ref missing); //} /// <summary> /// catches Word's open event /// just close /// </summary> /// <param name="doc"></param> private void OnOpenDoc(Word.Document doc) { //try //{ // if (doc != null && docFullName != doc.FullName) OnNewDoc(doc); //} //catch //{ //} }
/// <summary> /// catches Word's newdocument event /// just close /// </summary> /// <param name="doc"></param> private void OnNewDoc(Word.Document doc) { if (!deactivateevents) { //wd = null; //deactivateevents=true; //object dummy = null; string fileName = doc.FullName; //doc.Close(ref dummy,ref dummy,ref dummy); LoadDocument(fileName, true); //deactivateevents=false; } }
/// <summary> /// Opens the original word file and initializes the Word.Document object. /// The original file may be HTML, DOC, or RTF /// </summary> private void OpenWordDoc() { object fileNameAsObj = m_originalFileName; object readOnly = false; object isVisible = true; object confirmConversion = false; object missing = System.Reflection.Missing.Value; m_wordDoc = m_wordApp.Documents.Open( ref fileNameAsObj, ref confirmConversion, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); m_wordDoc.Activate(); m_wordDoc.WebOptions.Encoding = Office.MsoEncoding.msoEncodingUTF8; m_wordDoc.WebOptions.BrowserLevel = Word.WdBrowserLevel.wdBrowserLevelMicrosoftInternetExplorer5; m_wordDoc.WebOptions.OptimizeForBrowser = false; }
public void saveDoc(Word.Document doc, bool SaveInTable) { //our own function to be handled here if (!doc.ReadOnly) { doc.Save(); } ApplicationClass ap = new ApplicationClass(); while (ap.BackgroundSavingStatus > 0) { System.Threading.Thread.Sleep(250); } if (FileID != string.Empty && SaveInTable) { string content = doc.Content.Text; object dummy = null; wAppC.Documents.Close(ref dummy, ref dummy, ref dummy); wDoc = null; if (TableName == "tempdocs" && FileID != string.Empty) { TempDocManager.EditFile(FileID, filename, content); FileID = string.Empty; } else if (TableName == "filedocs" && FileID != string.Empty) { FileDocManager.EditFile(FileID, filename, content); FileID = string.Empty; } } //////else //////{ ////// if (!doc.ReadOnly ) ////// doc.Save(); //////} //////ApplicationClass ap = new ApplicationClass(); ////// while (ap.BackgroundSavingStatus > 0) //////{ ////// System.Threading.Thread.Sleep(250); //////} }
void FileTableHour(Word.Document wdoc, string beginTime, float[][] hisData, int[] count, int[] val) { Tables t = wdoc.Tables; DateTime date = DateTime.ParseExact(beginTime, "yyyyMMddHHmmss", null); //填写用户信息和日期 t[1].Cell(1, 2).Range.Text = Form1.gasname; t[1].Cell(2, 2).Range.Text = Form1.gasid; t[1].Cell(2, 4).Range.Text = date.Year.ToString("d4"); t[1].Cell(2, 6).Range.Text = date.Month.ToString("d2"); t[1].Cell(2, 8).Range.Text = date.Day.ToString("d2"); t[1].Cell(2, 10).Range.Text = date.Hour.ToString("d2"); for (int i = 0; i < 60; i++) { for (int j = 0; j < hisData.Length; j++) { if (val[j] == i) { t[2].Cell(2 + i, 1).Range.Text = date.Hour.ToString("d2") + ":" + i.ToString("d2"); //颗粒物 t[2].Cell(2 + i, 2).Range.Text = hisData[j][0].ToString("f1"); t[2].Cell(2 + i, 3).Range.Text = hisData[j][1].ToString("f1"); //SO2 t[2].Cell(2 + i, 4).Range.Text = hisData[j][3].ToString("f1"); t[2].Cell(2 + i, 5).Range.Text = hisData[j][4].ToString("f1"); //NOX t[2].Cell(2 + i, 6).Range.Text = hisData[j][6].ToString("f1"); t[2].Cell(2 + i, 7).Range.Text = hisData[j][7].ToString("f1"); //O2 t[2].Cell(2 + i, 8).Range.Text = hisData[j][10].ToString("f1"); float qiya = hisData[j][12]; float wendu = hisData[j][11]; float liuliang = hisData[j][13]; //流速 t[2].Cell(2 + i, 9).Range.Text = (liuliang / Form1.M2).ToString("f1"); //工况 t[2].Cell(2 + i, 10).Range.Text = (liuliang * 3600).ToString("f2"); //标杆 t[2].Cell(2 + i, 11).Range.Text = ((float)Form1.QswXishu * 3600 * liuliang * 273 * (qiya) * (1 - (float)Form1.Xsw) / ((273 + wendu) * 101325)).ToString("f2"); //温度 t[2].Cell(2 + i, 12).Range.Text = hisData[j][11].ToString("f1"); //break; } } } }
/// /// 打开Word文档,并且返回对象oDoc /// 完整Word文件路径+名称 /// 返回的Word.Document oDoc对象 public Word.Document CreateWordDocument(string FileName, bool HideWin) { if (FileName == "") { return(null); } OWordApplic.Visible = HideWin; OWordApplic.Caption = ""; OWordApplic.Options.CheckSpellingAsYouType = false; OWordApplic.Options.CheckGrammarAsYouType = false; Object filename = FileName; Object ConfirmConversions = false; Object ReadOnly = true; Object AddToRecentFiles = false; Object PasswordDocument = System.Type.Missing; Object PasswordTemplate = System.Type.Missing; Object Revert = System.Type.Missing; Object WritePasswordDocument = System.Type.Missing; Object WritePasswordTemplate = System.Type.Missing; Object Format = System.Type.Missing; Object Encoding = System.Type.Missing; Object Visible = System.Type.Missing; Object OpenAndRepair = System.Type.Missing; Object DocumentDirection = System.Type.Missing; Object NoEncodingDialog = System.Type.Missing; Object XMLTransform = System.Type.Missing; try { Word.Document wordDoc = OWordApplic.Documents.Open(ref filename, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate, ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format, ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection, ref NoEncodingDialog, ref XMLTransform); return(wordDoc); } catch (Exception ex) { MessageBox.Show(ex.Message); return(null); } }
//转化 public static void WordToHtmlFile(string WordFilePath, string htmlpath) { try { Word.Application newApp = new Word.Application(); // 指定原文件和目标文件 object Source = WordFilePath; //string SaveHtmlPath = WordFilePath.Substring(0, WordFilePath.Length - 3) + "html"; object Target = htmlpath; // 缺省参数 object Unknown = Type.Missing; //为了保险,只读方式打开 object readOnly = true; // 打开doc文件 Word.Document doc = newApp.Documents.Open(ref Source, ref Unknown, ref readOnly, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown); // 指定另存为格式(rtf) object format = Word.WdSaveFormat.wdFormatHTML; // 转换格式 doc.SaveAs(ref Target, ref format, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown); // 关闭文档和Word程序 doc.Close(ref Unknown, ref Unknown, ref Unknown); newApp.Quit(ref Unknown, ref Unknown, ref Unknown); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } }
void yearReport(DateTime dates) { try { if (dates > DateTime.Now) { MessageBox.Show("只能选择本月之前的日期查看"); return; } string date = Form1.str + "//年报表" + dates.Year.ToString("d4") + ".doc"; File.Copy(Form1.str + "//year.doc", date, true); this.axFramerControl1.Open(date); this.axFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileSave, false); this.axFramerControl1.Toolbars = false; this.axFramerControl1.Titlebar = false; //写保护,只能读取 Object myObj = this.axFramerControl1.ActiveDocument; if (myObj == null) { return; } Word.Document wdoc = (Word.Document)myObj; Word.Application ThisApplication = wdoc.Application; object missing = Type.Missing; //wdoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref missing, ref missing, ref missing, ref missing); try { FillCommonTable(wdoc, dates, "y"); } catch (Exception ex) { MessageBox.Show("adf" + ex.Message + ex.StackTrace); } } catch (Exception ex) { MessageBox.Show("创建月报表出错!" + ex.Message); } }
static void Main(string[] args) { // Find the full path of our document System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location); object docFileName = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "document.doc"); // Create the needed Word.Application and Word.Document objects object nullObject = System.Reflection.Missing.Value; Word.Application application = new Word.ApplicationClass(); Word.Document document = application.Documents.Open(ref docFileName, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject); string wholeTextContent = document.Content.Text; wholeTextContent = wholeTextContent.Replace('\r', ' '); // Delete lines between paragraphs string[] splittedTextContent = wholeTextContent.Split(' '); // Get the separate words int index = 1; foreach (string singleWord in splittedTextContent) { if (singleWord.Trim().Length > 0) // We don´t need to store white spaces { Console.WriteLine("Word: " + singleWord + "(position: " + index.ToString() + ")"); index++; } } // Dispose Word.Application and Word.Document objects resources document.Close(ref nullObject, ref nullObject, ref nullObject); application.Quit(ref nullObject, ref nullObject, ref nullObject); document = null; application = null; Console.ReadLine(); }
public void SaveAs(Word.Document oDoc, string strFileName) { object fileName = strFileName; if (File.Exists(strFileName)) { if (MessageBox.Show("文件'" + strFileName + "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK) { oDoc.SaveAs(ref fileName, 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); } else { Clipboard.Clear(); } } else { oDoc.SaveAs(ref fileName, 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> /// 附加dot模版文件 /// </summary> private void LoadDotFile(string strDotFile) { if (!string.IsNullOrEmpty(strDotFile)) { Word.Document wDot = null; if (OWordApplic != null) { ODoc = OWordApplic.ActiveDocument; OWordApplic.Selection.WholeStory(); //string strContent = oWordApplic.Selection.Text; OWordApplic.Selection.Copy(); wDot = CreateWordDocument(strDotFile, true); object bkmC = "Content"; if (OWordApplic.ActiveDocument.Bookmarks.Exists("Content") == true) { OWordApplic.ActiveDocument.Bookmarks.get_Item (ref bkmC).Select(); } //对标签"Content"进行填充 //直接写入内容不能识别表格什么的 //oWordApplic.Selection.TypeText(strContent); OWordApplic.Selection.Paste(); OWordApplic.Selection.WholeStory(); OWordApplic.Selection.Copy(); wDot.Close(ref missing, ref missing, ref missing); ODoc.Activate(); OWordApplic.Selection.Paste(); } } }
void FillCommonTable(Word.Document wdoc, DateTime date, string flag) { float[][] hisData = null; int[] count = null; int[] val = null; int tableRows = 0; bool hasdata = false; if (flag == "h") { string begintime = date.Year.ToString("d4") + date.Month.ToString("d2") + date.Day.ToString("d2") + date.Hour.ToString("d2") + "0000"; string endtime = date.Year.ToString("d4") + date.Month.ToString("d2") + date.Day.ToString("d2") + date.Hour.ToString("d2") + "5959"; hasdata = Form1.ReadRecordData(begintime, endtime, ref hisData, ref count, ref val, "mi"); tableRows = 60; //小时数据比较特殊,需要单独填写 FileTableHour(wdoc, begintime, hisData, count, val); return; } if (flag == "d") { string begintime = date.Year.ToString("d4") + date.Month.ToString("d2") + date.Day.ToString("d2") + "000000"; string endtime = date.Year.ToString("d4") + date.Month.ToString("d2") + date.Day.ToString("d2") + "235959"; hasdata = Form1.ReadRecordData(begintime, endtime, ref hisData, ref count, ref val, "h"); tableRows = 24; } else if (flag == "m") { string begintime = date.Year.ToString("d4") + date.Month.ToString("d2") + "01000000"; int days = DateTime.DaysInMonth(date.Year, date.Month); string endtime = date.Year.ToString("d4") + date.Month.ToString("d2") + days.ToString("d2") + "235959"; hasdata = Form1.ReadRecordData(begintime, endtime, ref hisData, ref count, ref val, "d"); tableRows = days; } else if (flag == "y") { string begintime = date.Year.ToString("d4") + "0101000000"; int days = DateTime.DaysInMonth(date.Year, date.Month); string endtime = date.Year.ToString("d4") + "0101235959"; hasdata = Form1.ReadRecordData(begintime, endtime, ref hisData, ref count, ref val, "m"); tableRows = 12; } if (!hasdata) { MessageBox.Show("没有查到数据,请重新选择日期!"); return; } List <int> tmpList = new List <int>(); for (int i = 0; i < val.Length; i++) { tmpList.Add(i); } for (int i = 0; i < val.Length; i++) { if (val[i] != -1) { tmpList.Remove(val[i]); } } for (int i = 0; i < val.Length; i++) { if (val[i] == -1) { val[i] = tmpList[0]; tmpList.Remove(tmpList[0]); } } Tables t = wdoc.Tables; //填写用户信息和日期 t[1].Cell(1, 2).Range.Text = Form1.gasname; t[1].Cell(2, 2).Range.Text = Form1.gasid; t[1].Cell(2, 4).Range.Text = date.Year.ToString("d4"); t[1].Cell(2, 6).Range.Text = date.Month.ToString("d2"); t[1].Cell(2, 8).Range.Text = date.Day.ToString("d2"); //首先填每行的前12列,这是具体的内容 for (int i = 0; i < tableRows; i++) { for (int j = 0; j < hisData.Length; j++) { if (val[j] == i) { for (int k = 0; k < 12; k++) { if (k == 2 || k == 5 || k == 8) { //日报表单位是kg,月报表和年报是顿 if (flag == "d") { t[2].Cell(3 + i, k + 2).Range.Text = (hisData[j][k]).ToString("f3"); } else if (flag == "m") { hisData[j][k] /= 1000; t[2].Cell(3 + i, k + 2).Range.Text = (hisData[j][k]).ToString("f4"); } else if (flag == "y") { hisData[j][k] /= 1000; t[2].Cell(3 + i, k + 2).Range.Text = (hisData[j][k]).ToString("f1"); } } else if (k == 9) { if (flag == "d") { t[2].Cell(3 + i, k + 2).Range.Text = (hisData[j][k]).ToString("f3"); } else if (flag == "m") { hisData[j][k] /= 10000; t[2].Cell(3 + i, k + 2).Range.Text = (hisData[j][k]).ToString("f3"); } else if (flag == "y") { hisData[j][k] /= 10000; t[2].Cell(3 + i, k + 2).Range.Text = (hisData[j][k]).ToString("f1"); } } else { if (flag == "d") { t[2].Cell(3 + i, k + 2).Range.Text = hisData[j][k].ToString("f3");; } else if (flag == "m") { t[2].Cell(3 + i, k + 2).Range.Text = hisData[j][k].ToString("f1");; } else if (flag == "y") { t[2].Cell(3 + i, k + 2).Range.Text = hisData[j][k].ToString("f1");; } } } t[2].Cell(3 + i, 12 + 2).Range.Text = "-"; t[2].Cell(3 + i, 13 + 2).Range.Text = "-"; t[2].Cell(3 + i, 14 + 2).Range.Text = "-"; break; } } } //填写平均值等4行 float[] max = null; float[] min = null; float[] avg = null; GetMinMax(hisData, ref max, ref min, ref avg); int total_count = 0; for (int i = 0; i < tableRows; i++) { total_count += count[i]; } float t1 = 0; float t2 = 0; float t3 = 0; float t4 = 0; for (int i = 0; i < tableRows; i++) { t1 += hisData[i][2]; t2 += hisData[i][5]; t3 += hisData[i][8]; t4 += hisData[i][9]; } if (flag == "m") { tableRows = 31; } for (int i = 0; i < 12; i++) { t[2].Cell(3 + tableRows, i + 2).Range.Text = avg[i].ToString("f1"); t[2].Cell(3 + tableRows + 1, i + 2).Range.Text = max[i].ToString("f1"); t[2].Cell(3 + tableRows + 2, i + 2).Range.Text = min[i].ToString("f1"); t[2].Cell(3 + tableRows + 3, i + 2).Range.Text = total_count.ToString(); } t[2].Cell(3 + tableRows, 12 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows, 13 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows, 14 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 1, 12 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 1, 13 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 1, 14 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 2, 12 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 2, 13 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 2, 14 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 3, 12 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 3, 13 + 2).Range.Text = "-"; t[2].Cell(3 + tableRows + 3, 14 + 2).Range.Text = "-"; //日报表总的排放量单位不一致 if (flag == "d") { t[2].Cell(3 + tableRows + 4, 3).Range.Text = (t1 / 1000).ToString("f3"); t[2].Cell(3 + tableRows + 4, 5).Range.Text = (t2 / 1000).ToString("f3"); t[2].Cell(3 + tableRows + 4, 7).Range.Text = (t3 / 1000).ToString("f3"); t[2].Cell(3 + tableRows + 4, 8).Range.Text = (t4 / 10000).ToString("f3"); } else { t[2].Cell(3 + tableRows + 4, 3).Range.Text = t1.ToString("f3"); t[2].Cell(3 + tableRows + 4, 5).Range.Text = t2.ToString("f3"); t[2].Cell(3 + tableRows + 4, 7).Range.Text = t3.ToString("f3"); t[2].Cell(3 + tableRows + 4, 8).Range.Text = t4.ToString("f3"); } }
public override void process(DataRow[] drTables, DataSet dsTableColumns, DataSet dsTablePrimaryKeys) { try { base.process(drTables, dsTableColumns, dsTablePrimaryKeys); OutPut = FilePathHelper.ExportDBDocPath; FileHelper.CreateDirectory(OutPut); setEnable(false); string msg = string.Empty; Stopwatch sw = Stopwatch.StartNew(); FileHelper.DeleteDirectory(FilePathHelper.ExportDBDocPath); if (drTables != null && dsTableColumns != null && dsTablePrimaryKeys != null) { setStatusBar(string.Format("正在生成{0}数据库文档", dbName)); setProgreesEditValue(0); setProgress(0); setProgressMax(drTables.Length); string path = FilePathHelper.ExportDBDocPath + dbName + "_DB_{0}_{1}" + ".doc"; FileHelper.CreateDirectory(path); Object Nothing = System.Reflection.Missing.Value; Word.Application dbWordApp = new Word.Application(); dbWordApp.NormalTemplate.Saved = true; Word.Document dbDoc = dbWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); dbWordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; dbWordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; dbWordApp.ActiveWindow.ActivePane.Selection.InsertAfter(string.Format("{0} {1}数据库文档", dbName, dbType)); dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; dbWordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; string tableName = ""; int begin = 0; int end = 0; #region try { for (int j = 0; j < drTables.Length; j++) { try { if ((j + 1) % num == 0 || (j + 1).Equals(drTables.Length)) { begin = end; end = j; } #region 样式 DataRow drTable = drTables[j]; DataRow[] drTableColumns = dsTableColumns.Tables[dbName + DBtablesColumns].Select( "TABLE_NAME = '" + drTable["name"].ToString() + "'", "COLUMN_ID ASC"); tableName = drTable["name"] as string; //表名 string tableComments = drTable["comments"] as string; //表说明 setStatusBar(string.Format("正在生成{0}中{1}表信息,共{2}张表,已生成了{3}张表", dbName, tableName, drTables.Length, j)); //Word段落 Word.Paragraph p; p = dbDoc.Content.Paragraphs.Add(ref Nothing); //设置段落中的内容文本 p.Range.Text = "表" + Convert.ToString(j + 1) + ":" + tableName + "(" + tableComments + ")"; //设置为一号标题 object style = Word.WdBuiltinStyle.wdStyleHeading1; p.set_Style(ref style); //添加到末尾 p.Range.InsertParagraphAfter(); style = Word.WdBuiltinStyle.wdStyleBodyText; p.set_Style(ref style); //dbWordApp.Selection.TypeText("表" + Convert.ToString(j + 1) + ":" + tableName + "(" + // tableComments + ")"); dbWordApp.Selection.ParagraphFormat.LineSpacing = 15f; object count = 20; object WdLine = Word.WdUnits.wdLine; dbWordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing); Word.Table newTable = dbDoc.Tables.Add(dbWordApp.Selection.Range, drTableColumns.Length + 2, 7, ref Nothing, ref Nothing); newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; newTable.Columns[1].Width = 110f; //列明 newTable.Columns[2].Width = 90f; //数据类型 newTable.Columns[3].Width = 50f; //是否NULL newTable.Columns[4].Width = 40f; //默认值 newTable.Columns[5].Width = 30f; //主键 newTable.Columns[6].Width = 30f; //外键 newTable.Columns[7].Width = 130f; //列说明 #endregion #region 填充表名称(表格内) newTable.Cell(1, 1).Range.Text = "表名:" + tableName + "(" + tableComments + ")"; newTable.Cell(1, 1).Range.Bold = 2; //设置单元格中字体为粗体 //合并单元格 newTable.Cell(1, 1).Merge(newTable.Cell(1, 7)); newTable.Cell(1, 1).Range.Font.Color = Word.WdColor.wdColorRed; //设置单元格内字体颜色 newTable.Cell(1, 1).Select(); //选中 dbWordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //垂直居中 dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 #endregion #region 填充列标题 newTable.Cell(2, 1).Range.Text = "列名"; newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 2).Range.Font.Bold = 2; newTable.Cell(2, 2).Range.Font.Size = 9; newTable.Cell(2, 2).Select(); //选中 newTable.Cell(2, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 newTable.Cell(2, 2).Range.Text = "数据类型"; newTable.Cell(2, 2).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 2).Range.Font.Bold = 2; newTable.Cell(2, 2).Range.Font.Size = 9; newTable.Cell(2, 2).Select(); //选中 newTable.Cell(2, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 newTable.Cell(2, 3).Range.Text = "是否NULL"; newTable.Cell(2, 3).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 3).Range.Font.Bold = 2; newTable.Cell(2, 3).Range.Font.Size = 9; newTable.Cell(2, 3).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(2, 3).Select(); //选中 dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 newTable.Cell(2, 4).Range.Text = "默认值"; newTable.Cell(2, 4).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 4).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(2, 4).Range.Font.Bold = 2; newTable.Cell(2, 4).Range.Font.Size = 9; newTable.Cell(2, 4).Select(); //选中 dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 newTable.Cell(2, 5).Range.Text = "主键"; newTable.Cell(2, 5).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 5).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(2, 5).Range.Font.Bold = 2; newTable.Cell(2, 5).Range.Font.Size = 9; newTable.Cell(2, 5).Select(); //选中 dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 newTable.Cell(2, 6).Range.Text = "外键"; newTable.Cell(2, 6).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 6).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(2, 6).Range.Font.Bold = 2; newTable.Cell(2, 6).Range.Font.Size = 9; newTable.Cell(2, 6).Select(); //选中 dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 newTable.Cell(2, 7).Range.Text = "备注"; newTable.Cell(2, 7).Range.Font.Color = Word.WdColor.wdColorBlack; //设置单元格内字体颜色 newTable.Cell(2, 7).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(2, 7).Range.Font.Bold = 2; newTable.Cell(2, 7).Range.Font.Size = 9; newTable.Cell(2, 7).Select(); //选中 dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 #endregion #region 填充表格内容 for (int i = 0; i < drTableColumns.Length; i++) { string tableColumnName = drTableColumns[i]["COLUMN_NAME"] as string; //列名 string tableColumnComments = drTableColumns[i]["COMMENTS"] as string; //列说明 string tableColumnDataType = drTableColumns[i]["DATA_TYPE"] as string; //列类型 string tableColumnDataScale = drTableColumns[i]["DATA_SCALE"] + ""; //列精度 string tableColumnDataLength = drTableColumns[i]["DATA_LENGTH"] + ""; //列长度 string tableColumnDataNullAble = drTableColumns[i]["NULLABLE"] as string; //可空 string tableColumnDataDefault = drTableColumns[i]["DATA_DEFAULT"] as string; //默认值 string tableColumnDataPrecision = drTableColumns[i]["Data_Precision"] + ""; if (string.IsNullOrEmpty(tableColumnDataPrecision)) //字符串、日期等 { if ("DATE".Equals(tableColumnDataType)) { tableColumnDataType = tableColumnDataType + "()"; } else { tableColumnDataType = tableColumnDataType + "(" + tableColumnDataLength + ")"; } } else //数字类型等 { if ("0".Equals(tableColumnDataScale)) { tableColumnDataType = tableColumnDataType + "(" + tableColumnDataPrecision + ")"; } else { tableColumnDataType = tableColumnDataType + "(" + tableColumnDataPrecision + "," + tableColumnDataScale + ")"; } } //列名 newTable.Cell(i + 3, 1).Range.Text = tableColumnName; newTable.Cell(i + 3, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; //数据类型 newTable.Cell(i + 3, 2).Range.Text = tableColumnDataType; newTable.Cell(i + 3, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; //是否Null newTable.Cell(i + 3, 3).Range.Text = tableColumnDataNullAble; newTable.Cell(i + 3, 3).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(i + 3, 3).Select(); dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 //默认值 newTable.Cell(i + 3, 4).Range.Text = tableColumnDataDefault; newTable.Cell(i + 3, 4).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(i + 3, 4).Select(); dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 //主键 newTable.Cell(i + 3, 5).Range.Text = ""; DataRow[] dr = dsTablePrimaryKeys.Tables[dbName + DBtablesPrimaryKeys].Select( "TABLE_NAME = '" + tableName + "' AND COLUMN_NAME ='" + tableColumnName + "' and constraint_type='P'"); if (dr != null && dr.Length > 0) { newTable.Cell(i + 3, 5).Range.Text = "Y"; } newTable.Cell(i + 3, 5).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(i + 3, 5).Select(); dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 //外键 newTable.Cell(i + 3, 6).Range.Text = ""; DataRow[] dr2 = dsTablePrimaryKeys.Tables[dbName + DBtablesPrimaryKeys].Select( "TABLE_NAME = '" + tableName + "' AND COLUMN_NAME ='" + tableColumnName + "' and constraint_type='R'"); if (dr2 != null && dr2.Length > 0) { newTable.Cell(i + 3, 6).Range.Text = "Y"; } newTable.Cell(i + 3, 6).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; newTable.Cell(i + 3, 6).Select(); dbWordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //水平居中 //说明 newTable.Cell(i + 3, 7).Range.Text = tableColumnComments; newTable.Cell(i + 3, 7).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } #endregion setProgress(1); } catch (Exception ex) { msg = ex.Message; string str = (string.Format("{0}生成数据库文档丢失{1}表", dbName, tableName)); setStatusBar(str); LogHelper.Error(ex); LogHelper.Debug(str); } finally { #region 释放资源 if ((j + 1) % num == 0 || (j + 1).Equals(drTables.Length)) { try { object fileName = string.Format(path, begin + 1, end + 1); dbDoc.SaveAs(ref fileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); } catch (Exception ex) { msg = ex.Message; LogHelper.Error(ex); } try { dbDoc.Close(ref Nothing, ref Nothing, ref Nothing); } catch { } if (dbDoc != null) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(dbDoc); } catch { } dbDoc = null; } GC.Collect(); if (!(j + 1).Equals(drTables.Length)) { dbDoc = dbWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); } } #endregion } } } catch (Exception ex) { msg = ex.Message; LogHelper.Error(ex); } finally { #region 释放资源 try { dbWordApp.Quit(ref Nothing, ref Nothing, ref Nothing); } catch { } if (dbWordApp != null) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(dbWordApp); } catch { } dbWordApp = null; } GC.Collect(); #endregion } #endregion } sw.Stop(); if (string.IsNullOrEmpty(msg)) { setStatusBar(string.Format("{0}数据库文档生成成功", dbName)); openDialog(); } else { setStatusBar(string.Format("{0}数据库文档生成失败[{1}]", dbName, msg)); } setEnable(true); } catch (Exception ex) { setStatusBar(string.Format("{0}数据库文档生成失败[{1}]", dbName, ex.Message)); } }
/// <summary> /// 导出后备干部考察材料表 /// </summary> /// <param name="idlist">需要导出后备干部的id号集合</param> public void exportword(ArrayList idlist) { //选择保存路径 #region string savepath = ""; SaveFileDialog sa = new SaveFileDialog(); sa.Filter = "Document(*.doc)|*.doc"; sa.FileName = "考察材料表"; if (sa.ShowDialog() == DialogResult.OK) { savepath = sa.FileName; } else { return; } #endregion //创建word应用程序 wordappliction = new Word.Application(); object filepath = System.Windows.Forms.Application.StartupPath + "\\wordModel" + "\\考察材料1.doc"; Word.Document mydoc = wordappliction.Documents.Open(ref filepath, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); //wordappliction.Visible = true; mydoc.ActiveWindow.Selection.WholeStory(); mydoc.ActiveWindow.Selection.Tables[1].Select(); mydoc.ActiveWindow.Selection.Copy(); for (int i = 1; i < idlist.Count; i++) { //插入分页符 #region Word.Paragraph para1; para1 = mydoc.Content.Paragraphs.Add(ref missing); object pBreak = (int)WdBreakType.wdSectionBreakNextPage; //控制位置 para1.Range.InsertBreak(ref pBreak); #endregion //粘贴剪贴板中的内容,同时加上加上备注。 para1.Range.Paste(); } string selectid = ""; for (int i = 0; i < idlist.Count; i++) { if (i == idlist.Count - 1) { selectid = selectid + "'" + idlist[i] + "'"; } else { selectid = selectid + "'" + idlist[i] + "',"; } } string sql = "select name,material,cid from TB_CommonInfo where isdelete=0 order by rank,joinTeam desc"; string cond = "cid in (" + selectid + ")"; DataOperation dataOp = new DataOperation(); DataTable datatableT = dataOp.GetOneDataTable_sql(sql); DataTable dt = new DataTable(); dt = datatableT.Clone(); DataView dv = datatableT.AsDataView(); dv.RowFilter = cond; dt = dv.ToTable(); for (int i = 0; i < dt.Rows.Count; i++) { mydoc.Tables[i + 1].Cell(1, 1).Range.Text = dt.Rows[i][0].ToString() + "同志考察材料"; mydoc.Tables[i + 1].Cell(2, 1).Range.Text = dt.Rows[i][1].ToString(); } #region object path = savepath; //wordappliction.Documents.Save(path); object myobj = System.Reflection.Missing.Value;; mydoc.SaveAs(ref path, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj); #endregion //关闭退出文档 #region //关闭文档 mydoc.Close(ref myobj, ref myobj, ref myobj); //退出应用程序。 wordappliction.Quit(); #endregion MessageBox.Show("导出成功!"); }
static void Main(string[] args) { object oMissing = Type.Missing; //System.Reflection.Missing.Value; Word.Application WordApp = null; Word.Document Document = null; Word.Table Table = null; string CurrentDirectory = System.IO.Directory.GetCurrentDirectory(), tmpString; CurrentDirectory = CurrentDirectory.Substring(0, CurrentDirectory.LastIndexOf("bin", CurrentDirectory.Length - 1)); object InputFileName, OutputFileName, tmpObject; try { try { try { WordApp = (Word.Application)Marshal.GetActiveObject("Word.Application"); } catch (COMException eException) { if (eException.ErrorCode == -2147221021) { WordApp = new Word.Application(); } } WordApp.Visible = true; #if TEST_BOOKMARK InputFileName = CurrentDirectory + "Word_tst.doc"; Document = WordApp.Documents.Open(ref InputFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); if (Document.Bookmarks.Count > 0) { tmpString = "MyBookmark"; if (Document.Bookmarks.Exists(tmpString)) { tmpObject = tmpString; #if TEST_BOOKMARK_BY_BOOKMARKS_COLLECTION Document.Bookmarks.Item(ref tmpObject).Select(); #else object What = Word.WdGoToItem.wdGoToBookmark; WordApp.Selection.GoTo(/*What*/ ref What, /*Which*/ ref oMissing, /*Count*/ ref oMissing, /*Name*/ ref tmpObject); #endif WordApp.Selection.Text = "1234567890"; } } OutputFileName = CurrentDirectory + "Word_tst_out.doc"; if (File.Exists(OutputFileName.ToString())) { File.Delete(OutputFileName.ToString()); } Document.SaveAs(ref OutputFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); Document.Close(ref oMissing, ref oMissing, ref oMissing); #endif Document = WordApp.Documents.Add(ref oMissing, ref oMissing); int index = 0, rows = 3, columns = 2; Table = Document.Tables.Add(WordApp.Selection.Range, rows + 1, columns); Table.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; Table.Range.Bold = 1; for (int i = 0; i < columns; i++) { Table.Cell(0, i + 1).Range.InsertAfter(i.ToString()); } for (int j = 1; j <= rows; j++) { Table.Rows.Item(j + 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; Table.Rows.Item(j + 1).Range.Bold = 0; for (int i = 0; i < columns; i++) { Table.Cell(j + 1, i + 1).Range.InsertAfter(index.ToString()); index++; } } OutputFileName = CurrentDirectory + "test_out.doc"; if (File.Exists(OutputFileName.ToString())) { File.Delete(OutputFileName.ToString()); } Document.SaveAs(ref OutputFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); Document.Close(ref oMissing, ref oMissing, ref oMissing); } catch (COMException eException) { string tmp = eException.GetType().FullName + Environment.NewLine + "ErrorCode: " + eException.ErrorCode + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace; Console.WriteLine(tmp); } catch (ArgumentException eException) { string tmp = eException.GetType().FullName + Environment.NewLine + "ParamName: " + eException.ParamName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace; Console.WriteLine(tmp); } catch (Exception eException) { string tmp = eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace; Console.WriteLine(tmp); } } finally { if (Table != null) { Marshal.ReleaseComObject(Table); Table = null; } if (Document != null) { Marshal.ReleaseComObject(Document); Document = null; } if (WordApp != null) { WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); Marshal.ReleaseComObject(WordApp); WordApp = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.GetTotalMemory(true); //GC.SuppressFinalize(this); } }
public void LoadDocument(string t_filename, string ID, string TableName, bool ManualOpen) { deactivateevents = true; FileID = ID; this.TableName = TableName; filename = t_filename; try { if (wAppC == null) { wAppC = new Word.ApplicationClass(); } try { wAppC.CommandBars.AdaptiveMenus = false; wAppC.DocumentBeforeClose += new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(OnClose); wAppC.NewDocument += new Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc); wAppC.DocumentOpen += new Word.ApplicationEvents2_DocumentOpenEventHandler(OnOpenDoc); wAppC.DocumentBeforeSave += new Word.ApplicationEvents2_DocumentBeforeSaveEventHandler(OnBeforSaveDoc); wAppC.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit); } catch { } if (wDoc != null) { try { object dummy = null; wAppC.Documents.Close(ref dummy, ref dummy, ref dummy); wordWnd = 0; } catch { } } if (wordWnd == 0) { wordWnd = FindWindow("Opusapp", null); } if (wordWnd != 0) { if (!ManualOpen) { SetParent(wordWnd, this.Handle.ToInt32()); } object fileName = filename; object newTemplate = false; object docType = 0; object readOnly = true; object isVisible = true; object missing = System.Reflection.Missing.Value; try { if (wAppC == null) { throw new WordInstanceException(); } if (wAppC.Documents == null) { throw new DocumentInstanceException(); } if (wAppC != null && wAppC.Documents != null) { //document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible); object file = fileName; //this is the path object nullobject = System.Reflection.Missing.Value; wDoc = wAppC.Documents.Open(ref file, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject); //MessageBox.Show(document.Path + document.FullName); } if (wDoc == null) { throw new ValidDocumentException(); } } catch { } try { wAppC.ActiveWindow.DisplayRightRuler = false; wAppC.ActiveWindow.DisplayScreenTips = false; wAppC.ActiveWindow.DisplayVerticalRuler = false; wAppC.ActiveWindow.DisplayRightRuler = false; wAppC.ActiveWindow.ActivePane.DisplayRulers = false; wAppC.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView; //wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;//wdWebView; // .wdNormalView; } catch { } /// Code Added /// Disable the specific buttons of the command bar /// By default, we disable/hide the menu bar /// The New/Open buttons of the command bar are disabled /// Other things can be added as required (and supported ..:) ) /// Lots of commented code in here, if somebody needs to disable specific menu or sub-menu items. /// int counter = wAppC.ActiveWindow.Application.CommandBars.Count; for (int i = 1; i <= counter; i++) { try { String nm = wAppC.ActiveWindow.Application.CommandBars[i].Name; /// MessageBox.Show("The menu:" + nm); ////int count_control1 = wd.ActiveWindow.Application.CommandBars[i].Controls.Count; ////for (int j = 1; j <= count_control1; j++) //////for (int j = 1; j <= count_control; j++) ////{ //// try //// { //// //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption); //// //wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false; //// } //// catch (Exception ex) { } ////} if (nm == "Standard") { //nm=i.ToString()+" "+nm; //MessageBox.Show(nm); int count_control = wAppC.ActiveWindow.Application.CommandBars[i].Controls.Count; for (int j = 1; j <= 2; j++) //for (int j = 1; j <= count_control; j++) { try { //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption); wAppC.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false; } catch (Exception ex) { } } } if (nm == "Menu Bar") { //To disable the menubar, use the following (1) line wAppC.ActiveWindow.Application.CommandBars[i].Enabled = false; /// If you want to have specific menu or sub-menu items, write the code here. /// Samples commented below // MessageBox.Show(nm); //int count_control=wd.ActiveWindow.Application.CommandBars[i].Controls.Count; //MessageBox.Show(count_control.ToString()); /* * //for(int j=1;j<=count_control;j++) * for(int j=1;j<=count_control-1;j++) * { * /// The following can be used to disable specific menuitems in the menubar * //wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled=false; * wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption = "سلام"; * wd.ActiveWindow.Application.CommandBars[i].Controls[j].Delete((object)true); * * ////MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString()); * ////MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption); * ////MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].accChildCount.ToString()); * * * ///The following can be used to disable some or all the sub-menuitems in the menubar * * * Office.CommandBarPopup c; * c = (Office.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[j]; * * for (int k = 1; k <= c.Controls.Count; k++) * { * //MessageBox.Show(k.ToString()+" "+c.Controls[k].Caption + " -- " + c.Controls[k].DescriptionText + " -- " ); * try * { * c.Controls[k].Enabled = false; * // c.Controls["Close Window"].Enabled = false; * } * catch * { * * } * } * * * * //wd.ActiveWindow.Application.CommandBars[i].Controls[j].Control Controls[0].Enabled=false; * } */ } nm = ""; } catch (Exception ex) { ErrorManager.WriteMessage("LoadDocument,t_filename", ex.ToString(), this.ParentForm.Text); MessageBox.Show(ex.ToString()); } } // Show the word-document try { wAppC.Visible = true; if (ManualOpen) { wAppC.Activate(); } if (!ManualOpen) { SetWindowPos(wordWnd, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE); } //Call onresize--I dont want to write the same lines twice OnResize(); } catch { MessageBox.Show("Error: do not load the document into the control until the parent window is shown!"); } /// We want to remove the system menu also. The title bar is not visible, but we want to avoid accidental minimize, maximize, etc ..by disabling the system menu(Alt+Space) try { int hMenu = GetSystemMenu(wordWnd, false); if (hMenu > 0) { int menuItemCount = GetMenuItemCount(hMenu); RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 7, MF_REMOVE | MF_BYPOSITION); RemoveMenu(hMenu, menuItemCount - 8, MF_REMOVE | MF_BYPOSITION); DrawMenuBar(wordWnd); } } catch { }; if (!ManualOpen) { this.Parent.Focus(); } } deactivateevents = false; } catch (Exception ex) { deactivateevents = false; ID = string.Empty; ErrorManager.WriteMessage("LoadDocument,t_filename2", ex.ToString(), this.ParentForm.Text); } }
/// <summary> /// 导出初步人选名册 /// </summary> /// <param name="idlist">传递所选干部的所有id</param> public void exportword(ArrayList idlist) { #region //选择保存路径 #region string savepath = ""; SaveFileDialog sa = new SaveFileDialog(); sa.Filter = "Document(*.doc)|*.doc"; sa.FileName = "初步人选名册"; if (sa.ShowDialog() == DialogResult.OK) { savepath = sa.FileName; } else { return; } #endregion //创建word应用程序 wordappliction = new Word.Application(); //打开模板 object filepath = System.Windows.Forms.Application.StartupPath + "\\wordModel" + "\\花名册.doc"; Word.Document mydoc = wordappliction.Documents.Open(ref filepath, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); //打开模板复制其中的表 #endregion //通过idlist读取所选后备干部的信息,用datatable存在内存中。 string selectid = ""; for (int i = 0; i < idlist.Count; i++) { if (i == idlist.Count - 1) { selectid = selectid + "'" + idlist[i] + "'"; } else { selectid = selectid + "'" + idlist[i] + "',"; } } string sql = "select name,cid,sex,nation,department,position,native,birthday,age,partyTime,workTime,fullEducation,fullDegree,fullSchool,fullSpecialty,workEducation,workDegree,workGraduate,workSpecialty,technicalPost,joinTeam,experiencePost,knowField,trainDirection,trainMeasure,partyClass from TB_CommonInfo order by rank,joinTeam desc"; string cond = "cid in (" + selectid + ")"; DataOperation dataOp = new DataOperation(); DataTable datatableT = dataOp.GetOneDataTable_sql(sql); DataTable datatable = new DataTable(); datatable = datatableT.Clone(); DataView dv = datatableT.AsDataView(); dv.RowFilter = cond; datatable = dv.ToTable(); //确定表头的单位信息 string title = null; if (this.Unitclass.Equals("省直单位")) { if (this.Qd.Equals("正职")) { title = this.Unit + "正厅级"; } else if (this.Qd.Equals("副职")) { title = this.Unit + "副厅级"; } } else if (this.Unitclass.Equals("省辖市")) { title = this.Unit + "党政" + this.Qd; } else if (this.Unitclass.Equals("省管高校")) { if (this.Qd.Equals("正职")) { title = this.Unit + "正校级"; } else if (this.Qd.Equals("副职")) { title = this.Unit + "副校级"; } } else if (this.Unitclass.Equals("省管企业")) { title = this.Unit + "领导班子" + this.Qd; }//县处级 else if (this.Unitclass.Equals("市直单位")) { if (this.Qd.Equals("正职")) { title = this.Unit + "正县级"; } else if (this.Qd.Equals("副职")) { title = this.Unit + "副县级"; } } else if (this.Unitclass.Equals("市管企业")) { title = this.Unit + "领导班子" + this.Qd; } else if (this.Unitclass.Equals("市管学校")) { if (this.Qd.Equals("正职")) { title = this.Unit + "正校级"; } else if (this.Qd.Equals("副职")) { title = this.Unit + "副校级"; } } else if (this.Unitclass.Equals("县(市、区)")) { title = this.Unit + "党政" + this.Qd; }//乡科级 else if (this.Unitclass.Equals("县(市、区)直")) { if (this.Qd.Equals("正职")) { title = this.Unit + "正科级"; } else if (this.Qd.Equals("副职")) { title = this.Unit + "副科级"; } } else if (this.Unitclass.Equals("县管学校")) { if (this.Qd.Equals("正职")) { title = this.Unit + "正校级"; } else if (this.Qd.Equals("副职")) { title = this.Unit + "副校级"; } } else if (this.Unitclass.Equals("县管企业")) { title = this.Unit + "领导班子" + this.Qd; } else if (this.Unitclass.Equals("乡(镇、街道)")) { title = this.Unit + "党政" + this.Qd; } mydoc.Tables[1].Cell(1, 1).Range.Text = title; mydoc.Tables[3].Cell(1, 1).Range.Text = title + "后备干部初步人选名册"; #region mydoc.ActiveWindow.Selection.WholeStory(); mydoc.ActiveWindow.Selection.Tables[4].Select(); mydoc.ActiveWindow.Selection.Copy(); #endregion //添加前面的说明信息 //以下几个变量用于后备干部信息的统计 int allcount = 0; //统计总人数 int mancount = 0; //记录男总人数 int womencoumt = 0; //记录女总人数 int unpartyount = 0; //记录非中共党员人数 int fewnationcount = 0; //记录少数民族人数 int age40 = 0; //记录40岁以下人数 int age41_45 = 0; //记录41到45岁人数 int age46_50 = 0; //记录46到50岁人数 int age51 = 0; //记录51岁以上人数 int doctorgraduate = 0; //记录博士研究生人数 int mastergraduate = 0; //记录硕士研究生人数 int graduate = 0; //记录大学生人数 string aveage = ""; //记录平均年龄 //所用到的一切信息统计结果 #region //总人数 allcount = datatable.Rows.Count; //男人数 DataTable datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and sex = '男'"); mancount = datatable1.Rows.Count; //女人数 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and sex = '女'"); womencoumt = datatable1.Rows.Count; //非中共 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and partyClass = '中共'"); unpartyount = allcount - datatable1.Rows.Count; //少数民族 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and nation like '%汉%'"); fewnationcount = allcount - datatable1.Rows.Count; //40岁及40岁以下 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and age <= 40"); age40 = datatable1.Rows.Count; //41岁到45岁 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and age > 40 and age <=45"); age41_45 = datatable1.Rows.Count; //46岁到50岁 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and age > 45 and age <=50"); age46_50 = datatable1.Rows.Count; //51岁以上 datatable1.Clear(); datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and age > 50"); age51 = datatable1.Rows.Count; //平均年龄 datatable1 = dataOp.GetOneDataTable_sql("select AVG(age) as aveage from TB_CommonInfo where cid in (" + selectid + ")"); aveage = datatable1.Rows[0]["aveage"].ToString(); //平均年龄计算结果可能为空 if (aveage.Equals("") || aveage == null) { aveage = "0"; } //博士 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and ((fullDegree = '博士' and (fullEducation='研究生' or fullEducation='党校研究生')) or (workDegree='博士' and (workEducation='研究生' or workEducation='党校研究生')))"); doctorgraduate = datatable1.Rows.Count; String doctor = ""; for (int i = 0; i < datatable1.Rows.Count; i++) { if (i == datatable1.Rows.Count - 1) { doctor = doctor + "'" + datatable1.Rows[i][0] + "'"; } else { doctor = doctor + "'" + datatable1.Rows[i][0] + "',"; } } //硕士 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and cid not in(" + doctor + ") and ((fullDegree = '硕士' and (fullEducation='研究生' or fullEducation='党校研究生')) or (workDegree='硕士' and (workEducation='研究生' or workEducation='党校研究生')))"); mastergraduate = datatable1.Rows.Count; String master = ""; for (int i = 0; i < datatable1.Rows.Count; i++) { if (i == datatable1.Rows.Count - 1) { master = master + "'" + datatable1.Rows[i][0] + "'"; } else { master = master + "'" + datatable1.Rows[i][0] + "',"; } } //学士 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and cid not in (" + doctor + ") and cid not in (" + master + ") and ((fullDegree = '学士' and (fullEducation='大学本科' or fullEducation='党校大学')) or (workDegree='学士' and (workEducation='大学本科' or workEducation='党校大学')))"); graduate = datatable1.Rows.Count; #endregion //表头和说明信息 #region string explain = " " + this.Unit + "党政" + this.Qd + "后备干部初步人选共" + allcount + "人,其中:男" + mancount + "人,女" + womencoumt + "人,非中共党员干部" + unpartyount + "人,少数民族干部" + fewnationcount + "人,40岁及以下" + age40 + "人,41-45岁" + age41_45 + "人,46-50岁" + age46_50 + "人,51岁以上" + age51 + "人,平均年龄" + Math.Round(Convert.ToDouble(aveage), 2) + "岁,博士研究生" + doctorgraduate + "人,硕士研究生" + mastergraduate + "人,大学" + graduate + "人。"; #endregion mydoc.Tables[2].Range.Text = explain; int tablecount1 = 0; if (datatable.Rows.Count % pagecount == 0) { tablecount1 = datatable.Rows.Count / pagecount - 1; } else { tablecount1 = datatable.Rows.Count / pagecount; } #region for (int i = 0; i < tablecount1; i++) { //第二页的前两行 Word.Paragraph para1 = mydoc.Content.Paragraphs.Add(ref missing); Word.Paragraph para2 = mydoc.Content.Paragraphs.Add(ref missing); Word.Paragraph para3 = mydoc.Content.Paragraphs.Add(ref missing); //在此粘贴复制的表格 //控制位置 object pBreak = (int)WdBreakType.wdSectionBreakNextPage; para1.Range.InsertBreak(ref pBreak); para3.Range.Paste(); if (i == tablecount1 - 1) { para3.Range.Text = " 注:后备干部人选是民主党派成员的,在“入党时间”栏填写党派名称及加入时间;无党派人士,此栏不填。"; } } if (tablecount1 == 0) { Word.Paragraph para1 = mydoc.Content.Paragraphs.Add(ref missing); para1.Range.Text = " 注:后备干部人选是民主党派成员的,在“入党时间”栏填写党派名称及加入时间;无党派人士,此栏不填。"; } #endregion for (int i = 0; i < datatable.Rows.Count; i++) { int tableindex = i / pagecount + 4; int rowindex = i % pagecount + 3; string strS = "", strN = ""; string Remarks = ""; if (datatable.Rows[i]["sex"].ToString().Trim() != "男") { strS = datatable.Rows[i]["sex"].ToString().Trim(); } if (datatable.Rows[i]["nation"].ToString().Trim() != "汉族") { strN = datatable.Rows[i]["nation"].ToString().Trim(); } if (strS != "" && strN == "") { Remarks = "(" + strS + ")"; } else if (strS != "" && strN != "") { Remarks = "(" + strS + "、" + strN + ")"; } else if (strS == "" && strN != "") { Remarks = "(" + strN + ")"; } mydoc.Tables[tableindex].Cell(rowindex, 1).Select(); mydoc.Tables[tableindex].Cell(rowindex, 1).Range.Text = Remarks; //在选中的位置添加文本 string strna = datatable.Rows[i]["name"].ToString() + "\n"; wordappliction.Selection.Font.Name = "宋体 "; wordappliction.Selection.Font.Size = 10.5f; wordappliction.Selection.TypeText(strna); try { mydoc.Tables[tableindex].Cell(rowindex, 2).Range.Text = datatable.Rows[i]["department"].ToString() + "\n" + datatable.Rows[i]["position"].ToString(); //"工作单位及职务"; mydoc.Tables[tableindex].Cell(rowindex, 3).Range.Text = datatable.Rows[i]["native"].ToString(); //"籍贯"; string age = datatable.Rows[i]["birthday"].ToString().Replace("年", "."); mydoc.Tables[tableindex].Cell(rowindex, 4).Range.Text = age.Replace("月", ""); //"出生年月"; string partytime = datatable.Rows[i]["partyTime"].ToString().Replace("年", "."); mydoc.Tables[tableindex].Cell(rowindex, 5).Range.Text = partytime.Replace("月", ""); //"入党时间"; string worktime = datatable.Rows[i]["workTime"].ToString().Replace("年", "."); mydoc.Tables[tableindex].Cell(rowindex, 6).Range.Text = worktime.Replace("月", "");; //"参加工作时间"; mydoc.Tables[tableindex].Cell(rowindex, 7).Range.Text = datatable.Rows[i]["fullEducation"].ToString() + "\n" + datatable.Rows[i]["fullDegree"].ToString(); //"学历学位"; mydoc.Tables[tableindex].Cell(rowindex, 8).Range.Text = datatable.Rows[i]["fullSchool"].ToString() + "\n" + datatable.Rows[i]["fullSpecialty"].ToString(); // "毕业院校及专业"; mydoc.Tables[tableindex].Cell(rowindex, 9).Range.Text = datatable.Rows[i]["workEducation"].ToString() + "\n" + datatable.Rows[i]["workDegree"].ToString(); //"学历学位"; mydoc.Tables[tableindex].Cell(rowindex, 10).Range.Text = datatable.Rows[i]["workGraduate"].ToString() + "\n" + datatable.Rows[i]["workSpecialty"].ToString(); //"毕业院校及专业"; mydoc.Tables[tableindex].Cell(rowindex, 11).Range.Text = datatable.Rows[i]["technicalPost"].ToString(); //"专业技术职务"; mydoc.Tables[tableindex].Cell(rowindex, 12).Range.Text = datatable.Rows[i]["experiencePost"].ToString(); //"历任主要职务"; mydoc.Tables[tableindex].Cell(rowindex, 13).Range.Text = datatable.Rows[i]["knowField"].ToString(); //"熟悉领域"; mydoc.Tables[tableindex].Cell(rowindex, 14).Range.Text = datatable.Rows[i]["trainDirection"].ToString(); //"培养方向"; mydoc.Tables[tableindex].Cell(rowindex, 15).Range.Text = datatable.Rows[i]["trainMeasure"].ToString(); //"培养措施"; } catch (Exception ex) { MessageBox.Show("导出失败,请重新操作!" + ex.Message); return; } } try { object path = savepath; //wordappliction.Documents.Save(path); object myobj = System.Reflection.Missing.Value;; mydoc.SaveAs(ref path, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj); //关闭文档 mydoc.Close(ref myobj, ref myobj, ref myobj); //退出应用程序。 wordappliction.Quit(); MessageBox.Show("导出成功!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void OnBeforSaveDoc(Word.Document doc, ref Boolean dummy, ref Boolean du) { //MessageBox.Show("before saving"); // wd.ActiveDocument.Save(); // saveDoc(doc); }
private static int pagecount = 5;//记录花名册一页显示多少条记录 /// <summary> /// 给初步人选名册表填值并导出 /// </summary> /// <param name="idlist">传递所选干部的所有id</param> public void exportword(ArrayList idlist) { #region //选择保存路径 #region string savepath = ""; SaveFileDialog sa = new SaveFileDialog(); sa.Filter = "Document(*.doc)|*.doc"; sa.FileName = "初步人选名册"; if (sa.ShowDialog() == DialogResult.OK) { savepath = sa.FileName; } else { return; } #endregion //创建word应用程序 wordappliction = new Word.Application(); //打开模板 object filepath = System.Windows.Forms.Application.StartupPath + "\\wordModel" + "\\花名册.doc"; Word.Document mydoc = wordappliction.Documents.Open(ref filepath, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); //wordappliction.Visible = true; //打开模板复制其中的表 #endregion string selectid = ""; for (int i = 0; i < idlist.Count; i++) { if (i == idlist.Count - 1) { selectid = selectid + "'" + idlist[i] + "'"; } else { selectid = selectid + "'" + idlist[i] + "',"; } } //读取干部的相关信息 string sql = "select name,sex,nation,department,position,native,birthday,age,partyTime,workTime,fullEducation,fullDegree,fullSchool,fullSpecialty,workEducation,workDegree,workGraduate,workSpecialty,technicalPost,experiencePost,knowField,trainDirection,trainMeasure,partyClass from TB_CommonInfo where cid in (" + selectid + ")"; DataOperation dataOp = new DataOperation(); System.Data.DataTable datatable = dataOp.GetOneDataTable_sql(sql); //确定表头的单位信息 string title = null; mydoc.Tables[1].Cell(1, 1).Range.Text = title; mydoc.Tables[3].Cell(1, 1).Range.Text = title + "初步人选名册"; #region mydoc.ActiveWindow.Selection.WholeStory(); mydoc.ActiveWindow.Selection.Tables[4].Select(); mydoc.ActiveWindow.Selection.Copy(); #endregion //添加前面的说明信息 //以下几个变量用于干部信息的统计 int allcount = 0; //统计总人数 int mancount = 0; //记录男总人数 int womencoumt = 0; //记录女总人数 int unpartyount = 0; //记录非中共党员人数 int fewnationcount = 0; //记录少数民族人数 int age40 = 0; //记录40岁以下人数 int age41_45 = 0; //记录41到45岁人数 int age46_50 = 0; //记录46到50岁人数 int age51 = 0; //记录51岁以上人数 int doctorgraduate = 0; //记录博士研究生人数 int mastergraduate = 0; //记录硕士研究生人数 int graduate = 0; //记录大学生人数 int aveage = 0; //记录平均年龄 //所用到的一切信息统计结果 #region //总人数 allcount = datatable.Rows.Count; //男人数 DataTable datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and sex = '男'"); mancount = datatable1.Rows.Count; //女人数 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and sex = '女'"); womencoumt = datatable1.Rows.Count; //非中共 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and partyClass = '中共'"); unpartyount = allcount - datatable1.Rows.Count; //少数民族 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and nation like '%汉%'"); fewnationcount = allcount - datatable1.Rows.Count; //年龄段统计 int sum_age = 0; datatable1 = dataOp.GetOneDataTable_sql("select * from TB_CommonInfo where cid in (" + selectid + ") "); for (int i = 0; i < datatable1.Rows.Count; i++) { //获取当前年份 int year = System.DateTime.Now.Year; //获取当前月份 int month = System.DateTime.Now.Month; //获取出生年份 string str2 = datatable1.Rows[i]["birthday"].ToString().Substring(0, 4); //出生月份 string str3 = datatable1.Rows[i]["birthday"].ToString().Substring(5, 2); sum_age = sum_age + (year - Convert.ToInt32(str2)); if (Convert.ToInt32(str3) < month) { if ((year - Convert.ToInt32(str2) - 1) <= 40) { age40++; } if ((year - Convert.ToInt32(str2) - 1) > 40 && (year - Convert.ToInt32(str2)) <= 45) { age41_45++; } if ((year - Convert.ToInt32(str2) - 1) > 45 && (year - Convert.ToInt32(str2)) <= 50) { age46_50++; } if ((year - Convert.ToInt32(str2) - 1) > 50) { age51++; } } else { if ((year - Convert.ToInt32(str2)) <= 40) { age40++; } if ((year - Convert.ToInt32(str2)) > 40 && (year - Convert.ToInt32(str2)) <= 45) { age41_45++; } if ((year - Convert.ToInt32(str2)) > 45 && (year - Convert.ToInt32(str2)) <= 50) { age46_50++; } if ((year - Convert.ToInt32(str2)) > 50) { age51++; } } } aveage = (int)sum_age / datatable1.Rows.Count; //博士 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and fullDegree = '博士'"); doctorgraduate = datatable1.Rows.Count; //硕士 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and fullDegree = '硕士'"); mastergraduate = datatable1.Rows.Count; //学士 datatable1 = dataOp.GetOneDataTable_sql("select CID from TB_CommonInfo where cid in (" + selectid + ") and fullDegree = '学士'"); graduate = datatable1.Rows.Count; #endregion //表头和说明信息 #region string explain = " " + "初步人选共" + allcount + "人,其中:男" + mancount + "人,女" + womencoumt + "人,非中共党员干部" + unpartyount + "人,少数民族干部" + fewnationcount + "人,40岁及以下" + age40 + "人,41-45岁" + age41_45 + "人,46-50岁" + age46_50 + "人,51岁以上" + age51 + "人,平均年龄" + Math.Round(Convert.ToDouble(aveage), 2) + "岁,博士研究生" + doctorgraduate + "人,硕士研究生" + mastergraduate + "人,大学" + graduate + "人。"; #endregion mydoc.Tables[2].Range.Text = explain; int tablecount1 = 0; if (datatable.Rows.Count % pagecount == 0) { tablecount1 = datatable.Rows.Count / pagecount - 1; } else { tablecount1 = datatable.Rows.Count / pagecount; } #region for (int i = 0; i < tablecount1; i++) { //第二页的前两行 Word.Paragraph para1 = mydoc.Content.Paragraphs.Add(ref missing); Word.Paragraph para2 = mydoc.Content.Paragraphs.Add(ref missing); Word.Paragraph para3 = mydoc.Content.Paragraphs.Add(ref missing); //在此粘贴复制的表格 //控制位置 object pBreak = ( int )WdBreakType.wdSectionBreakNextPage; para1.Range.InsertBreak(ref pBreak); para3.Range.Paste(); if (i == tablecount1 - 1) { para3.Range.Text = " 注:干部人选是民主党派成员的,在“入党时间”栏填写党派名称及加入时间;无党派人士,此栏不填。"; } } if (tablecount1 == 0) { Word.Paragraph para1 = mydoc.Content.Paragraphs.Add(ref missing); para1.Range.Text = " 注:干部人选是民主党派成员的,在“入党时间”栏填写党派名称及加入时间;无党派人士,此栏不填。"; } #endregion for (int i = 0; i < datatable.Rows.Count; i++) { int tableindex = i / pagecount + 4; int rowindex = i % pagecount + 3; string strS = "", strN = ""; string Remarks = ""; if (datatable.Rows[i]["sex"].ToString().Trim() != "男") { strS = datatable.Rows[i]["sex"].ToString().Trim(); } if (datatable.Rows[i]["nation"].ToString().Trim() != "汉族") { strN = datatable.Rows[i]["nation"].ToString().Trim(); } if (strS != "" && strN == "") { Remarks = "(" + strS + ")"; } else if (strS != "" && strN != "") { Remarks = "(" + strS + "、" + strN + ")"; } else if (strS == "" && strN != "") { Remarks = "(" + strN + ")"; } mydoc.Tables[tableindex].Cell(rowindex, 1).Select(); mydoc.Tables[tableindex].Cell(rowindex, 1).Range.Text = Remarks; //在选中的位置添加文本 string strna = datatable.Rows[i]["name"].ToString() + "\n"; wordappliction.Selection.Font.Name = "宋体 "; wordappliction.Selection.Font.Size = 10.5f; wordappliction.Selection.TypeText(strna); try { mydoc.Tables[tableindex].Cell(rowindex, 2).Range.Text = datatable.Rows[i]["department"].ToString() + "\n" + datatable.Rows[i]["position"].ToString(); //"工作单位及职务"; mydoc.Tables[tableindex].Cell(rowindex, 3).Range.Text = datatable.Rows[i]["native"].ToString(); //"籍贯"; string age = datatable.Rows[i]["birthday"].ToString().Replace("年", "."); mydoc.Tables[tableindex].Cell(rowindex, 4).Range.Text = age.Replace("月", ""); //"出生年月"; string partytime = datatable.Rows[i]["partyTime"].ToString().Replace("年", "."); mydoc.Tables[tableindex].Cell(rowindex, 5).Range.Text = partytime.Replace("月", ""); //"入党时间"; string worktime = datatable.Rows[i]["workTime"].ToString().Replace("年", "."); mydoc.Tables[tableindex].Cell(rowindex, 6).Range.Text = worktime.Replace("月", ""); //"参加工作时间" mydoc.Tables[tableindex].Cell(rowindex, 7).Range.Text = datatable.Rows[i]["fullEducation"].ToString() + "\n" + datatable.Rows[i]["fullDegree"].ToString(); //"学历学位"; mydoc.Tables[tableindex].Cell(rowindex, 8).Range.Text = datatable.Rows[i]["fullSchool"].ToString() + "\n" + datatable.Rows[i]["fullSpecialty"].ToString(); // "毕业院校及专业"; mydoc.Tables[tableindex].Cell(rowindex, 9).Range.Text = datatable.Rows[i]["workEducation"].ToString() + "\n" + datatable.Rows[i]["workDegree"].ToString(); //"学历学位"; mydoc.Tables[tableindex].Cell(rowindex, 10).Range.Text = datatable.Rows[i]["workGraduate"].ToString() + "\n" + datatable.Rows[i]["workSpecialty"].ToString(); //"毕业院校及专业"; mydoc.Tables[tableindex].Cell(rowindex, 11).Range.Text = datatable.Rows[i]["technicalPost"].ToString(); //"专业技术职务"; mydoc.Tables[tableindex].Cell(rowindex, 12).Range.Text = datatable.Rows[i]["experiencePost"].ToString(); //"历任主要职务"; mydoc.Tables[tableindex].Cell(rowindex, 13).Range.Text = datatable.Rows[i]["knowField"].ToString(); //"熟悉领域"; mydoc.Tables[tableindex].Cell(rowindex, 14).Range.Text = datatable.Rows[i]["trainDirection"].ToString(); //"培养方向"; mydoc.Tables[tableindex].Cell(rowindex, 15).Range.Text = datatable.Rows[i]["trainMeasure"].ToString(); //"培养措施"; } catch (Exception ex) { MessageBox.Show("导出失败,请重新操作!" + ex.Message); return; } } #region object path = savepath; //wordappliction.Documents.Save(path); object myobj = System.Reflection.Missing.Value; ; mydoc.SaveAs(ref path, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj); #endregion //关闭退出文档 #region //关闭文档 mydoc.Close(ref myobj, ref myobj, ref myobj); //退出应用程序。 wordappliction.Quit(); #endregion MessageBox.Show("导出成功!"); }