Beispiel #1
0
    public static void Word2Format(object G_FilePath, object P_str_path, Word.WdSaveFormat wdf)
    {
        Word.Application G_wa;                                        //定义Word应用程序字段
        object           G_missing = System.Reflection.Missing.Value; //定义G_missing字段并添加引用

        //创建应用程序对象
        G_wa         = new Microsoft.Office.Interop.Word.Application();
        G_wa.Visible = false;
        //打开Word文档
        Word.Document P_wd = G_wa.Documents.Open(
            ref G_FilePath, 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);
        object P_Format = wdf;//创建保存文档参数

        //保存Word文件
        try
        {
            P_wd.SaveAs(
                ref P_str_path,
                ref P_Format, 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);
        }
        catch { }
        ((Word._Application)G_wa.Application).Quit(//退出应用程序
            ref G_missing, ref G_missing, ref G_missing);
    }
Beispiel #2
0
    protected void btn_CreatePDF_Click(object sender, EventArgs e)
    {
        string str_PdfFilename, str_mulu;
        string str_DocFilename;

        str_mulu = "./2015课题成果/研究报告/";
        string        str_MapPath = Server.MapPath(str_mulu);
        DirectoryInfo di          = new DirectoryInfo(str_MapPath);

        FileInfo[] dis = di.GetFiles();//取目录中所有内容
        for (int i = 0; i < dis.Length; i++)
        {
            str_DocFilename = dis[i].Name;
            str_PdfFilename = str_DocFilename.Substring(0, str_DocFilename.LastIndexOf(".")) + ".pdf";
            try
            {
                Microsoft.Office.Interop.Word.WdSaveFormat wdf = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
                WordToal.Word2Format(str_MapPath + str_DocFilename, str_MapPath + str_PdfFilename, wdf);
            }
            catch (Exception ee)
            {
                CommFun.error_record(Session["jsh"].ToString(), Session["jsm"].ToString(), ee.Message);
            }
        }
    }
Beispiel #3
0
 /// <summary>
 /// Copies a document to a specified path.
 /// </summary>
 /// <param name="document">The Document instance.</param>
 /// <param name="path">The path where the new file will be saved.</param>
 /// <param name="saveFormat">The save format.</param>
 /// <exception cref="IOException">When the file cannot be saved.</exception>
 /// <remarks>The document is saved in Unicode little endian encoding.</remarks>
 /// <returns>True if the operation succedes. False otherwise.</returns>
 public bool ShadowCopyDocument(Word.Document document, string path, Word.WdSaveFormat saveFormat)
 {
     try
     {
         Object format               = saveFormat;
         Object copyPath             = path;
         Object encoding             = MsoEncoding.msoEncodingUTF8;
         Object missing              = Type.Missing;
         Object originalFilePath     = document.FullName;
         Object initialDocSaveFormat = document.SaveFormat;
         document.SaveAs(ref copyPath, ref format, ref missing, ref missing, ref missing, ref missing,
                         ref missing, ref missing, ref missing, ref missing, ref missing, ref encoding,
                         ref missing, ref missing, ref missing, ref missing);
         //Refresh the active instance(required after acquiring chart data from Excel)
         document = addin.Application.ActiveWindow.Document;
         document.SaveAs(ref originalFilePath, ref initialDocSaveFormat, 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);
     }
     catch (IOException ioex)
     {
         Log.Exception(ioex);
         UserNotifier.Error(ioex.Message);
         return(false);
     }
     catch (Exception ex)
     {
         Log.Exception(ex);
         return(false);
     }
     return(true);
 }
Beispiel #4
0
    protected void bindData()
    {
        str_sql = "SELECT Status,sqr,xmbh,zqbg_dName,zqbg from t_teacher_list where appNo = '" + Session["appNo"].ToString() + "';";
        DataRow dr = DBFun.GetDataRow(str_sql);

        if (dr == null)
        {
            return;
        }

        string str_status = dr["Status"].ToString();

        cbx_1.Checked = (str_status == "6");

        string str_sqr = dr["sqr"].ToString();
        string str_xmbh = dr["xmbh"].ToString();
        string str_DocFilename = dr["zqbg"].ToString();
        string str_HtmlFilename, str_mulu;

        str_mulu = "./中期检查申请表/";
        if (str_DocFilename == "")
        {
            Response.Write("<script>alert('尚未上传期中检查申请表!');</script>");
            hl_1.ForeColor   = System.Drawing.Color.Red;
            hl_1.Text        = "尚未上传期中检查申请表";
            hl_1.NavigateUrl = "";
            return;
        }
        str_HtmlFilename = str_DocFilename.Substring(0, str_DocFilename.LastIndexOf(".")) + ".pdf";
        string str_MapPath = Server.MapPath(str_mulu);

        //if (!File.Exists(str_MapPath + str_filename))
        //{
        //    Response.Write("<script>alert('尚未上传期中检查申请表!');</script>");
        //    return;
        //}
        //File.Copy(str_MapPath + str_filename, str_MapPath + str_newfilename, true);
        hl_1.ForeColor = System.Drawing.Color.FromArgb(000066);
        hl_1.Text      = "查看中级检查申请表";
        //string str_oldfilename = Server.MapPath(str_filename + ".doc");
        try
        {
            word.WdSaveFormat wdf = word.WdSaveFormat.wdFormatPDF;
            WordToal.Word2Format(str_MapPath + str_DocFilename, str_MapPath + str_HtmlFilename, wdf);
        }
        catch
        { }
        hl_1.NavigateUrl = str_mulu + str_HtmlFilename;
    }
Beispiel #5
0
        public static string ConvertWord(string DocFilePathRaw, string NewFileName, string DirectoryToSaveRaw,
                                         string NewFileExtension, Word.WdSaveFormat NewFileFormat)
        {
            //calculate file name with exxtension
            if (!NewFileName.EndsWith("." + NewFileExtension))
            {
                NewFileName = NewFileName + "." + NewFileExtension;
            }

            //get absolute filePaths for both the new directory and the old file path
            string directoryToSave = String.IsNullOrEmpty(DirectoryToSaveRaw) ? Directory.GetCurrentDirectory() : Path.GetFullPath(DirectoryToSaveRaw);
            string docFilePath     = Path.GetFullPath(DocFilePathRaw);

            //calculate new File Path
            string newFilePath = Path.Combine(directoryToSave, NewFileName);

            // Open the Word Application.
            Word._Application word_app = new Word.Application();
            word_app.Visible       = false;
            word_app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

            //initialize settings
            bool   confirm_conversions = false;
            bool   read_only           = true;
            bool   add_to_recent_files = false;
            bool   save_changes        = false;
            object format = 0;

            //open the document
            Word._Document word_doc = word_app.Documents.Open(docFilePath, confirm_conversions, read_only, add_to_recent_files, Type.Missing,
                                                              Type.Missing, Type.Missing, Type.Missing,
                                                              Type.Missing, Type.Missing, Type.Missing,
                                                              Type.Missing, Type.Missing, Type.Missing,
                                                              Type.Missing, Type.Missing);

            word_doc.SaveAs(newFilePath, NewFileFormat,
                            Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing);

            //Close the document and the App
            word_doc.Close(save_changes, Type.Missing, Type.Missing);
            word_app.Quit();
            GC.Collect();

            return(newFilePath);
        }
Beispiel #6
0
        public void SaveDocument(Word.Document document, Word.WdSaveFormat format, string fileName)
        {
            Log.Verbose("Save_Document() -- Begin");

            try
            {
                document.SaveAs(fileName, format);
            }
            catch (Exception exception)
            {
                Log.Error("Error while saving the file.");
                Log.Error(exception.Message);
            }

            Log.Verbose("Save_Document() -- End");
        }
Beispiel #7
0
        public static void ConvertMod(string input, string output, Word.WdSaveFormat format)
        {
            // Create an instance of Word.exe
            Word._Application oWord     = new Word.Application();
            object            oMissing  = System.Reflection.Missing.Value;
            object            isVisible = true;
            object            readOnly  = false;
            object            oInput    = input;
            object            oOutput   = output;
            object            oFormat   = format;

            try
            {
                // Make this instance of word invisible (Can still see it in the taskmgr).
                oWord.Visible = false;

                // Load a document into our instance of word.exe
                Word._Document oDoc = oWord.Documents.Open(ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing,
                                                           ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                           ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing,
                                                           ref oMissing);

                // Make this document the active document.
                oDoc.Activate();

                oDoc.PageSetup.LeftMargin   = 15;
                oDoc.PageSetup.RightMargin  = 15;
                oDoc.PageSetup.TopMargin    = 15;
                oDoc.PageSetup.BottomMargin = 15;


                // Save this document in Word 2003 format.
                oDoc.SaveAs(ref oOutput, 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);

                // Always close Word.exe.
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception e)
            {
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                throw e;
            }
        }
Beispiel #8
0
        private void Save(string fileName, Microsoft.Office.Interop.Word.WdSaveFormat format)
        {
            switch (format)
            {
            case Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault:
                fileName = string.Format("{0}.docx", fileName);
                break;

            case Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF:
                fileName = string.Format("{0}.pdf", fileName);
                break;
            }
            object objFileName   = fileName,
                   objMissing    = Type.Missing,
                   objFalse      = false,
                   objTrue       = true,
                   objFileFormat = format;

            _document.SaveAs(ref objFileName, ref objFileFormat);
            WriteLog(string.Format("文件 {0} 已保存!\r\n", fileName));
        }
Beispiel #9
0
    protected void bindData()
    {
        str_sql = "SELECT sqr,xmbh,rws_dName,rws from t_teacher_list where xmbh = '" + Session["xmbh"].ToString() + "';";
        DataRow dr = DBFun.GetDataRow(str_sql);

        if (dr == null)
        {
            return;
        }
        string str_sqr = dr["sqr"].ToString();
        string str_xmbh = dr["xmbh"].ToString();
        string str_DocFilename = dr["rws"].ToString();
        string str_HtmlFilename, str_mulu;

        str_mulu = "./任务书/";
        if (str_DocFilename == "")
        {
            Response.Write("<script>alert('尚未上传期任务书!');</script>");
            hl_1.ForeColor   = System.Drawing.Color.Tomato;
            hl_1.Text        = "尚未上传期任务书";
            hl_1.NavigateUrl = "";
            return;
        }
        str_HtmlFilename = str_DocFilename.Substring(0, str_DocFilename.LastIndexOf(".")) + ".pdf";
        string str_MapPath = Server.MapPath(str_mulu);

        hl_1.ForeColor = System.Drawing.Color.FromArgb(000066);
        hl_1.Text      = "查看任务书";
        try
        {
            word.WdSaveFormat wdf = word.WdSaveFormat.wdFormatPDF;
            WordToal.Word2Format(str_MapPath + str_DocFilename, str_MapPath + str_HtmlFilename, wdf);
        }
        catch (Exception e)
        {
            CommFun.error_record(Session["jsh"].ToString(), Session["jsm"].ToString(), e.Message);
            return;
        }
        hl_1.NavigateUrl = str_mulu + str_HtmlFilename;
    }
Beispiel #10
0
        public string Convert()
        {
            if (!new System.IO.FileInfo(_destinationFilePath).Exists)
            {
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                wordApp.Visible       = false;
                wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                object wordTrue  = (object)true;
                object wordFalse = (object)false;


                Microsoft.Office.Interop.Word.WdSaveFormat fltDocFormatTemp = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;
                object fltDocFormat = fltDocFormatTemp;// 10;
                //For filtered HTML Output



                object missing    = Type.Missing;
                object fileToOpen = _sourceFilePath;
                Microsoft.Office.Interop.Word.Document doc1 = wordApp.Documents.Open(ref fileToOpen,
                                                                                     ref missing, ref wordFalse, ref wordFalse, ref missing,
                                                                                     ref missing, ref missing, ref missing, ref missing,
                                                                                     ref missing, ref missing, ref wordTrue, ref missing,
                                                                                     ref missing, ref missing, ref missing);

                object tempFile = _destinationFilePath;
                doc1.SaveAs2(ref tempFile, ref fltDocFormat, ref missing, ref missing, ref wordFalse, ref missing, ref wordTrue, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref wordTrue, ref missing);


                try
                {
                    doc1.Close();
                }
                finally { }
            }
            return(_destinationFilePath);
        }
Beispiel #11
0
        private void saveDoc(string ext, string extName, string fullExtName, Word.WdSaveFormat saveFormat)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter       = fullExtName + "|*" + ext;
            sfd.Title        = "Save an " + ext + " file";
            sfd.AddExtension = true;
            sfd.DefaultExt   = extName;

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Object templatePathObj = sfd.FileName;
            Object fileForm        = ext;

            _application = new Word.Application();
            try
            {
                _document = _application.Documents.Add(ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
            }
            catch (Exception error)
            {
                this.closeDoc();
                throw error;
            }
            object start = 0;
            object end   = 0;

            _currentRange        = _document.Range(ref start, ref end);
            _currentRange.Text   = textBox.Text;
            _application.Visible = false;

            _document.SaveAs(ref templatePathObj, saveFormat, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
            closeDoc();
        }
Beispiel #12
0
        public void SaveDocument(string pathToSave, Word.WdSaveFormat saveFormat)
        {
            Object pathToSaveObj = pathToSave;

            document.SaveAs(ref pathToSaveObj, saveFormat, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);
        }
Beispiel #13
0
		protected DocXmlDocument ConvertDocToXml(Word.Application wrdApp, string strDocFilename)
		{
			object oDocFilename = strDocFilename;
			Word._Document wrdDoc = wrdApp.Documents.Open(ref oDocFilename, ref oFalse, ref oFalse,
				ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
				ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
				ref oMissing);

			m_strExtnOpen = Path.GetExtension(strDocFilename);
			if (!String.IsNullOrEmpty(m_strExtnOpen))
			{
				m_strExtnOpen = m_strExtnOpen.ToLower();
				m_oFormatOpen = (Word.WdSaveFormat)wrdDoc.SaveFormat;
#if DEBUG && false
				MessageBox.Show(String.Format("File opened as format: '{0}'", m_oFormatOpen.ToString()));
#endif
			}

			bool bWord2007 = (wrdDoc.SaveFormat >= (int)wdFormatXMLDocument);
			if (bWord2007)
			{
				if (m_bWarnAboutWord2007Conversion)
				{
					DialogResult res = MessageBox.Show(String.Format("The document '{0}' can be processed if you use Word 2003 compatibility mode, though you may lose some formatting. Would you like to use Word 2003 compatibility mode on this and all subsequent Word 2007 documents?", strDocFilename), cstrCaption, MessageBoxButtons.YesNoCancel);
					if (res == DialogResult.No)
						return null;
					m_bWarnAboutWord2007Conversion = false;
				}
				bWord2007 = false;  // use Word 2003 compatibility mode
			}

			string strXmlFilename = GetTempFilename + ".xml";
			object oXmlFilename = strXmlFilename;
			object oXmlFormat = (bWord2007) ? wdFormatFlatXML : Word.WdSaveFormat.wdFormatXML;

			wrdDoc.SaveAs(ref oXmlFilename, ref oXmlFormat, ref oMissing, ref oMissing, ref oFalse, ref oMissing,
				ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
				ref oMissing, ref oMissing, ref oMissing);

			wrdDoc.Close(ref oMissing, ref oMissing, ref oMissing);

			DocXmlDocument doc =
#if !DefineWord07MLDocument
				(bWord2007) ? Word07MLDocument.GetXmlDocument(strXmlFilename) :
#endif
				Word03MLDocument.GetXmlDocument(strXmlFilename, strDocFilename);

			try
			{
				if (leaveXMLFileInFolderToolStripMenuItem.Checked)
				{
					int nIndex = strDocFilename.LastIndexOf('.');
					if (nIndex != -1)
					{
						strXmlFilename = String.Format(@"{0}\{1}{2}",
							Path.GetDirectoryName(strDocFilename),
							Path.GetFileName(strDocFilename),
							cstrLeftXmlFileSuffixBefore);
						if (File.Exists(strXmlFilename))
							File.Delete(strXmlFilename);
					}
				}
				doc.Save(strXmlFilename);
			}
			catch (Exception ex)
			{
				string strErrorMsg = String.Format("Unable to save a copy of the xml file in the local folder (requested by \"Advanced\", \"Leave XML file in folder\" option)! Reason:{0}{0}{1}{0}{0}Would you like to continue with the conversion process anyway?",
					Environment.NewLine, ex.Message);
				DialogResult res = MessageBox.Show(strErrorMsg, cstrCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error);
				if (res != DialogResult.Yes)
					return null;
			}
			return doc;
		}
Beispiel #14
0
 public FormatInfo(string name, string description, string defaultFileExtension, Word.WdSaveFormat saveFormat)
 {
     _name                 = name;
     _description          = description;
     _defaultFileExtension = defaultFileExtension;
     _saveFormat           = (int)saveFormat;
 }