ASP. NET Export word Instance

  • 2021-09-16 06:37:37
  • OfStack

Recently encountered a topic is how to export data to word in asp. net. Because the data is dynamic, it is necessary to spell out the desired format in the background. I searched the web page and found a satisfactory code. Thanks to the master. The code is as follows:


public void Download()
  {
   Random rd = new Random();
   string fileName = DateTime.Now.ToString("yyyyMMddhhmm") + rd.Next() + ".doc";
   // Storage path 
   string path = Server.MapPath(fileName);
   // Create character output stream 
   StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8);
   // What needs to be exported 
   // string str = "<html><head><title> Untitled document </title></head><body> Here is the exported from the database word Document content </body></html>";
   string str = "";
   str += "<html><head><title> Untitled document </title></head><body>";
   str += "<div> Read the report </div>";
   str += "<table border='1'><tr>";
   str += "<td>20000</td>";
   str += "<td>10000</td></tr><tr>";
   str += "<td>30000</td>";
   str += "<td>30000</td><tr>";
   str += "</table></body></html>";
   // Write 
   sw.Write(str);
   sw.Close();
   Response.Clear();
   Response.Buffer = true;
   this.EnableViewState = false;
   Response.Charset = "utf-8";
   Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
   Response.ContentType = "application/octet-stream";
   Response.WriteFile(path);
   Response.Flush();
   Response.Close();
   Response.End();
  }

Related articles: