none
Export Text to Word RRS feed

  • Question

  • I want to export a string of data to a new Microsoft Word Document. I have code already to do it in plain text and as RTF but I want to do it for word. Below is a class I made for exporting data currently. I would like to add a function to export to a word document.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Windows.Forms;
    
    namespace Sharp_Control.Data_Helpers
    {
        class Export_Functions
        {
    
            public bool Export_To_Rich_Text_Document(string Save_Path, string Document)
            {
                try
                {
                    if (!File.Exists(Save_Path))
                    {
                        string createText = Document + Environment.NewLine;
                        File.WriteAllText(Save_Path, createText);
                    }
                    
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
    }

    Friday, December 9, 2016 3:57 PM

Answers

All replies

  • I got this but it gives an error:

    public bool Export_To_Word(string Save_Path, string Document)
            {
                try
                {
                    //Create an instance for word app
                    Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                    
                    //Set status for word application is to be visible or not.
                    winword.Visible = false;
    
                    //Create a missing variable for missing value
                    object missing = System.Reflection.Missing.Value;
    
                    //Create a new document
                    Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                    
                    //adding text to document
                    document.Content.SetRange(0, 0);
                    document.Content.Text = Document + Environment.NewLine;
    
                    //Save the document
                    object filename = @"c:\temp1.docx";
                    //object filename = "@" + Save_Path + ".docx";
                    document.SaveAs2(ref filename);
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                    winword.Quit(ref missing, ref missing, ref missing);
                    winword = null;
                    MessageBox.Show("Document created successfully !");
    
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }


    Error:

    System.AccessViolationException was unhandled
      HResult=-2147467261
      Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
      Source=Sharp_Control
      StackTrace:
           at Microsoft.Office.Interop.Word._Document.SaveAs2(Object& FileName, Object& FileFormat, Object& LockComments, Object& Password, Object& AddToRecentFiles, Object& WritePassword, Object& ReadOnlyRecommended, Object& EmbedTrueTypeFonts, Object& SaveNativePictureFormat, Object& SaveFormsData, Object& SaveAsAOCELetter, Object& Encoding, Object& InsertLineBreaks, Object& AllowSubstitutions, Object& LineEnding, Object& AddBiDiMarks, Object& CompatibilityMode)
           at Sharp_Control.Data_Helpers.Export_Functions.Export_To_Word(String Save_Path, String Document) in E:\Sharp_Control\Sharp_Control\Data Helpers\Export_Functions.cs:line 55
           at Sharp_Control.ctrlPoliciesProcedures.ctrl_Click(Object sender, EventArgs e) in E:\Sharp_Control\Sharp_Control\ctrlPoliciesProcedures.cs:line 349
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at Sharp_Control.Program.Main() in E:\Sharp_Control\Sharp_Control\Program.cs:line 20
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:

    • Edited by old_School Friday, December 9, 2016 4:56 PM
    Friday, December 9, 2016 4:55 PM
  • Any help would be great, so far everything I've tried throws a memory access exception. I've tried every example I've found via google and all throws errors.
    Friday, December 9, 2016 7:10 PM
  • Did you try to save the file into a directory under your own user account and not 'C:\temp1.docx'. MS Office is very choosy about user access rights.

    wizend

    Friday, December 9, 2016 7:54 PM
  • Hi old_School,

    Thank you for posting here.

    According to your question is more related to Word, I will move it to Word for Developers forum for suitable support.

    The Visual C# Forum discuss and ask the question about the C# programming language, IDE, libraries, samples and tools.

    If you have some grammar or code errors, please feel free to contact us. We will try our best to give you a solution.

    Thanks for your understanding and cooperation.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 12, 2016 6:07 AM
  • Its a pretty simple direct c# related question. I have a rich text box with data and I want to export the data from a string to a Word Docx. I don't think that's related to Microsoft grammar. Please read. Thank you
    Monday, December 12, 2016 3:56 PM
  • Hi,

      object filename = "@" + Save_Path + ".docx";  This is an invalid filename. You need to remove the @.

    But I still failed to reproduce your issue.

    When saving into C:\ , I got the exception shown as follow.

    If saving into other location like desktop, it works fine.

    I would suggest you save into other disks.

    I think it is an environment issue. If you  Uncheck option "Suppress JIT optimization on module load" in Tools menu ->Options -> Debugging -> General, would it help?

    Please visit the two similar thread:

    Attempted to read or write protected memory. This is often an indication that other memory is corrupt

    Wierd error : Attempted to read or write protected memory. This is often an indication that other memory is corrupt

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by old_School Thursday, January 26, 2017 10:35 PM
    Tuesday, December 13, 2016 6:18 AM
    Moderator