开发者

To create msword document through asp mvc 1.0

开发者 https://www.devze.com 2023-03-01 18:46 出处:网络
Hii I am using asp.net MVC1.0. I want to create Ms word document through code I am using function : public ActionResult GetPostOffline(string PostId)

Hii I am using asp.net MVC1.0. I want to create Ms word document through code I am using function :

public ActionResult GetPostOffline(string PostId)

{
    Post post = new Post();
    post = PostBLL.PostDetails(new Guid(PostId.Replace("'","")));
    string strBody =  post.Title +post.Body;
    string filename = post.Title + ".doc";
    Response.Con开发者_JS百科tentType = "application/word";
    Response.AppendHeader("Content-disposition", "attachment; filename=" + filename);
    Response.Write(strBody);
    return View("~/Views/Posts/AllPosts.aspx");
}

It is correctly opening a word document but in that document it is not showing proper content . Instead of showing content it's is displaying HTML of my website.. What should i do .. please help me


Try like this:

public ActionResult GetPostOffline(string postId)
{
    Post post = new Post();
    post = PostBLL.PostDetails(new Guid(PostId.Replace("'","")));
    string strBody =  post.Title + post.Body;
    string filename = post.Title + ".txt";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
    return File(Encoding.UTF8.GetBytes(strBody), "text/plain");
}

I have modified the Content-Type from application/word to text/plain as what you have is a simple sting variable (strBody) and not an actual Word document. In order to create an MSWord document you will need some library.


I believe there is a simpler solution. From your question, it looks like you want the file to open up in word, even if it is just plain text. Here is my solution:

{
    Post post = new Post();
    post = PostBLL.PostDetails(new Guid(PostId.Replace("'","")));
    string strBody =  "<body>" + post.Title + System.Environment.NewLine + post.Body + "</body>";
    string filename = post.Title + ".doc";
    return File(Encoding.UTF8.GetBytes(strBody), "application/word", filename);
}

I added the System.Environment.NewLine between the title and body. Not sure if it is necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消