我想将Microsoft Word文档转换为.txt格式并将其保存在我的解决方案文件夹中

时间:2014-06-22 12:42:25

标签: c# asp.net ms-word office-interop

我正在使用文件上传器控件,我需要将上传的.docx文件转换为.txt 文件我使用了下面的一些代码:

object missingType = Type.Missing;
object readOnly = true;
object isVisible = false;
object format = WdSaveFormat.wdFormatText;
string randomName = DateTime.Now.Ticks.ToString();
FileUpload1.SaveAs(Server.MapPath("~/TextDoc/") + Path.GetFileName(FileUpload1.PostedFile.FileName));
object fileName = FileUpload1.PostedFile.FileName;
object txtFilePath = Server.MapPath("~/TextDoc/") + randomName + ".txt";
//Open the word document in background
ApplicationClass applicationclass = new ApplicationClass();
applicationclass.Documents.Open(ref fileName,
                                ref readOnly,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref isVisible,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType);
applicationclass.Visible = false;
Document document = applicationclass.ActiveDocument;


//Save the word document as txt file
document.SaveAs(ref txtFilePath, ref format, ref missingType,
                ref missingType, ref missingType, ref missingType,
                ref missingType, ref missingType, ref missingType,
                ref missingType, ref missingType, ref missingType,
                ref missingType, ref missingType, ref missingType,
                ref missingType);

//Close the word document
document.Close(ref missingType, ref missingType, ref missingType);

我将'filename'变量更改为

object fileName = "~/" + Path.GetFullPath(FileUpload1.FileName);

然后我得到例外:

This command is not available because no document is open.

请任何人帮助我..

3 个答案:

答案 0 :(得分:0)

您可以使用DocX来读取/操作不依赖于Office或Interop的Word文档。

查找DocX Here

项目所有者Cathal Coffey发布了各种DocX主题HERE

我使用DocX HERE

做了一篇快速而肮脏的“入门”类型文章

使用DocX来提取Word文档的文本然后保存为普通的.txt文件应该相对简单。

我通常不会在SO回答中发布链接。然而,在这种情况下,由于我只是指向一个完成工作的替代工具,这似乎是合适的。

答案 1 :(得分:0)

由于将物理路径传递给“Open method”,我得到了这些错误。

最后,我在解决方案中采用了另一个文件夹来存储上传的word文档,我通过了 文件路径为“open method”。我编辑了如下代码:

FileUpload1.SaveAs(Server.MapPath("~/WordDoc/")+Path.GetFileName(FileUpload1.PostedFile.FileName));
object fileName = Server.MapPath("~/WordDoc/"+Path.GetFileName(FileUpload1.PostedFile.FileName));

我将转换后的.txt文件保存在与之前相同的其他文件夹中(代码有问题)。 转换后我删除了word文档(上传或存储在“WordDoc”文件夹中),如:

File.Delete(Server.MapPath("~/WordDoc/") + Path.GetFileName(FileUpload1.PostedFile.FileName));

答案 2 :(得分:0)

请尝试使用以下行替换document.SaveAs方法中的第二个参数(ref格式):

Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatUnicodeText

这会将您的word文档保存为txt文件。

相关问题