保存javascript生成的文档

发布于 2024-08-06 09:37:39 字数 1635 浏览 4 评论 0原文

JavaScript 可以操作浏览器正在显示的文档,因此如下:

<script>
    document.write("<table><tr><td>Hola</td><td>Adios</td></tr></table>");
</script>

将使浏览器显示一个表格,就像它是原始 HTML 文档一样:

<table>
    <tr>
        <td>Hola</td>
        <td>Adios</td>
    </tr>
</table>

有没有办法可以保存/提供此文档内容?

目前我们有一些使用 Ext-js 生成的精美报告,我想做的是拥有它的“text/html”版本(我的意思是,不需要 javascript 的东西)

所以在页面末尾我将添加一个按钮:“另存为 blaba”,文档应显示文本/纯文本版本。

我现在能想到的唯一方法是将内容写入 JavaScript 变量,例如:

 var content = document.toString(); // or something magic like that.
 // post it to the server

然后将该值发布到服务器,并让服务器呈现该值。

 <%=request.getParameter("content-text")%>

但看起来非常棘手。

还有其他选择吗?

编辑

好吧,我差不多明白了。现在我只需要弹出新窗口,以便选择“您想保存它吗?显示”

这就是我到目前为止所得到的

<script>
    document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
    function saveAs(){
        var sMarkup =  document.getElementById('content').innerHTML; 
        var oNewDoc = document.open('application/vnd.ms-excel');        
        oNewDoc.write( sMarkup + "<hr>" );
        oNewDoc.close();
    }
</script>

<input type="button" value="Save as" onClick="saveAs()"/>

行:

    var oNewDoc = document.open('application/vnd.ms-excel');        

应该指定新的内容类型,但它被忽略了。

Javascript can manipulate the document the browser is displaying, so the following:

<script>
    document.write("<table><tr><td>Hola</td><td>Adios</td></tr></table>");
</script>

Will make the browser display a table just like if it was the original HTML document:

<table>
    <tr>
        <td>Hola</td>
        <td>Adios</td>
    </tr>
</table>

Is there a way I can save/serve this document content?

Currently we have some nicely generated reports using Ext-js, what I would like to do is to have the "text/html" version of it ( I mean, something that doesn't require javascript )

So at the end of the page I would add a button : "Save as blaba" and the document should display the text/plain version.

The only way I could think right now is, to write the content into a javascript variable like:

 var content = document.toString(); // or something magic like that.
 // post it to the server

Then post that value to the server, and have the server present that value.

 <%=request.getParameter("content-text")%>

But looks very tricky.

Is there an alternative?

EDIT

Ok, I almost got it. Now I just need the new window to pop up so the option "would you like to save it shows"

This is what I've got so far

<script>
    document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
    function saveAs(){
        var sMarkup =  document.getElementById('content').innerHTML; 
        var oNewDoc = document.open('application/vnd.ms-excel');        
        oNewDoc.write( sMarkup + "<hr>" );
        oNewDoc.close();
    }
</script>

<input type="button" value="Save as" onClick="saveAs()"/>

The line:

    var oNewDoc = document.open('application/vnd.ms-excel');        

Should specify the new content type, but it is being ignored.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

我乃一代侩神 2024-08-13 09:37:39

除非它被保存在客户端 File ->将页面另存为...,您必须完全按照您的建议进行操作,将 $('body').html() 发布到您的服务器并将其作为文本处理。

Unless its being saved client side with File -> Save Page As..., you will have to do exactly what you are proposing, posting $('body').html() to your server and process it as text.

裸钻 2024-08-13 09:37:39

这是以 .xls 格式打开表格内容的升级版本。

<head>
<script>

         document.write("<table id='targetTable'><tr><td>Hola</td><td>Adios</td></tr><tr><td>eins</td><td>zwei</td></table>"); 
        function saveAsXLS()
        {
            var xlObj = new ActiveXObject("Excel.Application");
            var xlBook = xlObj.Workbooks.Add();
            var xlSheet = xlBook.Worksheets(1);
            for (var y=0;y<targetTable.rows.length;y++) // targetTable=id of the table
            {
                for (var x=0;x<targetTable.rows(y).cells.length;x++)
                {
                    xlSheet.Cells(y+1,x+1)=targetTable.rows(y).cells(x).innerText;
                }
            }   
            xlObj.Visible=true;
            document.write("The table contents are opened in a new Excel sheet.");//Print on webpage 
        }
</script>
</head>
<body>  
<input type="button" value="Open table in Excel!" onclick="saveAsXLS()"/> 
</body>

此代码在 IE6 中进行了测试,并使用 ActiveXObject 控件。

  • 我在这里使用的表格大小为 2x2,各个内容分别映射到 Excel 工作表中。
  • 与 .doc 版本不同,这不会将文件保存在客户端系统中。它打开包含表内容的应用程序,客户端必须保存它。

希望这有助于回答您的问题。让我知道您是否遇到任何问题。

和平。

Here's the upgraded version to open the table contents in .xls format.

<head>
<script>

         document.write("<table id='targetTable'><tr><td>Hola</td><td>Adios</td></tr><tr><td>eins</td><td>zwei</td></table>"); 
        function saveAsXLS()
        {
            var xlObj = new ActiveXObject("Excel.Application");
            var xlBook = xlObj.Workbooks.Add();
            var xlSheet = xlBook.Worksheets(1);
            for (var y=0;y<targetTable.rows.length;y++) // targetTable=id of the table
            {
                for (var x=0;x<targetTable.rows(y).cells.length;x++)
                {
                    xlSheet.Cells(y+1,x+1)=targetTable.rows(y).cells(x).innerText;
                }
            }   
            xlObj.Visible=true;
            document.write("The table contents are opened in a new Excel sheet.");//Print on webpage 
        }
</script>
</head>
<body>  
<input type="button" value="Open table in Excel!" onclick="saveAsXLS()"/> 
</body>

This code is tested in IE6 and is using ActiveXObject control.

  • The table I've used here is of order 2x2 and the individual contents are mapped respectively into the excel sheet.
  • Unlike the .doc version, this does not save the file in client's system. It opens the application with the table content and the client has to save it.

Hope this helps in answering ur question. Lemme know if u face any issues.

Peace.

↘紸啶 2024-08-13 09:37:39

根据您的浏览器支持要求,您可以使用 数据 URI

Core 进行概念验证(在Firefox 3.5.3):

document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function extract(){
  return document.getElementById('content').innerHTML; 
}
function dataURI(s){
  return 'data:application/vnd.ms-excel;base64,' + encode64(s);
}
document.write('<a href="' + dataURI(extract()) + '">open</a>');

我从在线示例中提取了 Base 64 编码/解码。小心:我抓到的那个在 Base 64 编码之前包含了 URI 编码,这让我困惑了一段时间。

Depending on your browser support requirements, you could use data URIs

Core for proof of concept (tested in Firefox 3.5.3):

document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function extract(){
  return document.getElementById('content').innerHTML; 
}
function dataURI(s){
  return 'data:application/vnd.ms-excel;base64,' + encode64(s);
}
document.write('<a href="' + dataURI(extract()) + '">open</a>');

I pulled base 64 encode/decode from examples online. Careful: the one I grabbed included a URI encode before base 64 encode that messed me up for a while.

溇涏 2024-08-13 09:37:39

你已经接近我认为的答案了。问题是 'document.open(...)' 可以 仅采用标准 mime 类型,例如“text/html”、“text/plain”和其他一些

因此,您的代码应该是:

<script>
    document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
    function saveAs(){
        var sMarkup =  document.getElementById('content').innerHTML; 
        var oNewDoc = document.open('text/html');        
        oNewDoc.write( sMarkup + "<hr>" );
        oNewDoc.close();
    }
</script>

<input type="button" value="Save as" onClick="saveAs()"/>

希望这会有所帮助。

You are getting close to the answer I thinks. The problem is that 'document.open(...)' can only take standard mime-types such as 'text/html', 'text/plain' and a few others

And because of that your code should be:

<script>
    document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
    function saveAs(){
        var sMarkup =  document.getElementById('content').innerHTML; 
        var oNewDoc = document.open('text/html');        
        oNewDoc.write( sMarkup + "<hr>" );
        oNewDoc.close();
    }
</script>

<input type="button" value="Save as" onClick="saveAs()"/>

Hope this helps.

嘿咻 2024-08-13 09:37:39
$(function(){
    $('.bbutton').click(function(){
        var url='data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html() )
        location.href=url
        return false
    })
})
.table{background:#ddd;border:1px solid #aaa;}
.table thead th{border-bottom:1px solid #bbb;}
.table tr td{background:#eee;border-bottom:1px solid #fff;
  border-left:1px solid #ddd;text-align:center;}
.table tr:hover td{background:#fff;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='tableWrap'><table style='width:98%;box-shadow:none;' class='table'>
<thead><th>id</th><th>Name</th><th>Address</th></thead>
  <tr><td>1</td><td>Jyoti Telecom Services</td><td>http://www.tsjyoti.com</td></tr>
  <tr><td>2</td><td>Recharge</td><td>http://recharge.tsjyoti.com</td></tr>
  <tr><td>3</td><td>Bhuri Bharaj</td><td>http://bhuribharaj.tsjyoti.com</td></tr>
  </table></div>

<p>Your download's ready as Excel Sheet <a href='#'class='bbutton'>Click Here for download</a></p>

$(function(){
    $('.bbutton').click(function(){
        var url='data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html() )
        location.href=url
        return false
    })
})
.table{background:#ddd;border:1px solid #aaa;}
.table thead th{border-bottom:1px solid #bbb;}
.table tr td{background:#eee;border-bottom:1px solid #fff;
  border-left:1px solid #ddd;text-align:center;}
.table tr:hover td{background:#fff;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='tableWrap'><table style='width:98%;box-shadow:none;' class='table'>
<thead><th>id</th><th>Name</th><th>Address</th></thead>
  <tr><td>1</td><td>Jyoti Telecom Services</td><td>http://www.tsjyoti.com</td></tr>
  <tr><td>2</td><td>Recharge</td><td>http://recharge.tsjyoti.com</td></tr>
  <tr><td>3</td><td>Bhuri Bharaj</td><td>http://bhuribharaj.tsjyoti.com</td></tr>
  </table></div>

<p>Your download's ready as Excel Sheet <a href='#'class='bbutton'>Click Here for download</a></p>

别念他 2024-08-13 09:37:39

如果它只是一个报告,您可以使用服务器端 JavaScript 来生成它,然后使用您需要的任何 MIME 类型提供它......

If it's just a report, you could use server-side JavaScript to generate it, and then serve it up with whatever MIME type you need...

伪装你 2024-08-13 09:37:39

我不认为将 html 发送到服务器是一个棘手的解决方案。您只需记住向您的用户提供下载此文件的链接即可。这可以使用传统的 POST 甚至 AJAX 来完成。这取决于您希望用户如何在页面上进行交互。

使用传统的帖子,您可以将所有 html 内容放入隐藏在页面中的输入类型的 value 属性中,命名为“html_content”或类似的名称,当用户单击“保存”按钮时,您会将用户发送到另一个带有链接的页面执行该文件。您将 html 发送到服务器,脚本在文件系统中创建一个具有唯一名称的文件,并返回下载链接。

使用 AJAX,您只需要执行 AJAX POST 传递此变量,然后您的脚本返回一个下载链接,然后动态地将其放入 html 中 - 无需重新加载页面,就像它是“仅客户端”一样。

无论哪种方式,您都会返回一个指向刚刚在文件系统中创建的资源的链接,扩展名为 html。请记住在服务器中为每个生成的文件生成唯一的名称,以避免冲突。

请注意,在 IE 6 中使用innerHTML(我不知道这是 IE 系列行为还是只是 6 版本)会将所有标签大写并删除属性中的引号。如果您打算在 html 中进行一些后期处理,请小心。

我不知道 jQuery 或其他 JS 库在这种情况下的行为如何。我建议使用它,他们有大量的浏览器兼容性检查来抽象我们使用的所有这些黑客。

I dont think that sending your html to the server is a tricky solution. You just have to remember to give a link to your user to download this file. This can be done using a traditional POST, or even using AJAX. It depends on how you want your users to interact if your page.

Using traditional post, you could put all the html content in the value attribute of an input type hidden in your page, named "html_content" or something like that, and when the user clicks in the button "save" you send your user to another page with a link do the file. You send the html to server, a script creates a file in a filesystem with an unique name, and returns a download link.

Using AJAX, you just need to do an AJAX POST passing this variable, and then your script returns a download link, and you dynamically put it in your html - without reloading your page, like it was "only cliente side".

Either way, you'll return a link to the resource you just created in your filesystem with a html extension. Remember to generate unique names in your server for each generated file to avoid collisions.

Beware though that using innerHTML in IE 6 (I dont know if this is a IE family behavior or just about the 6 version) uppercases all tags and removes quotes from attributes. If you're planning to do some post processing in your html, be careful.

I dont know how jQuery or other JS libraries behaves in such situations. I would suggest using it though, they have plenty of browser compatibility checks to abstract all these hacks we use.

怎言笑 2024-08-13 09:37:39

这是我的代码,用于将 JavaScript 生成的内容[客户端]以 MSWord[.doc] 格式保存到本地 C: 驱动器。

<script>

    document.write("<div id='content'><table><tr><td>Holaa</td><td>Adiosa</td></tr></table></div>"); 
    function saveAs()
        {
            var wordObj=new ActiveXObject("Word.Application");
            var docText;
            var obj;
            var textToWrite = document.getElementById('content').innerHTML;
            if (wordObj != null)
            {
                wordObj.Visible = false;
                wordDoc=wordObj.Documents.Add();
                wordObj.Selection.TypeText(textToWrite);
                wordDoc.SaveAs("C:\\Eureka.doc");
                wordObj.Quit();
                document.write("The content has been written to 'C:\\Eureka.doc'");//Print on webpage 
            }
        }
</script>

<body>

<input type="button" value="Save in C:" onclick="saveAs()"/> 

</body>

我很快就解决了你的问题并想出了这段代码。希望我正确理解你的问题。

我的代码中的限制是

  • 文件格式是 .doc 而不是 .xls。
  • 其次,文件保存在静态位置而不是用户指定的位置[可以优化]。
  • 而且,代码使用了ActiveX,我没有检查服务器端环境中的工作情况。

这些需要在即将发布的版本中解决。 (:

和平。

Here's my code to save the generated content[client-side] by the JavaScript to the local C: drive in MSWord[.doc] format.

<script>

    document.write("<div id='content'><table><tr><td>Holaa</td><td>Adiosa</td></tr></table></div>"); 
    function saveAs()
        {
            var wordObj=new ActiveXObject("Word.Application");
            var docText;
            var obj;
            var textToWrite = document.getElementById('content').innerHTML;
            if (wordObj != null)
            {
                wordObj.Visible = false;
                wordDoc=wordObj.Documents.Add();
                wordObj.Selection.TypeText(textToWrite);
                wordDoc.SaveAs("C:\\Eureka.doc");
                wordObj.Quit();
                document.write("The content has been written to 'C:\\Eureka.doc'");//Print on webpage 
            }
        }
</script>

<body>

<input type="button" value="Save in C:" onclick="saveAs()"/> 

</body>

I quickly worked on ur issue and came up with this piece of code. Hope I understood your issue correctly.

The contraints in my code are

  • File format is .doc and not .xls.
  • Secondly, The file is saved in a static location and not the user specified location[can be optimized].
  • And, the code uses ActiveX and I didnot check the working in server-side environment.

These need to be addressed in the upcoming versions. (:

Peace.

谁的新欢旧爱 2024-08-13 09:37:39

您的 javascript AJAX 是从服务器获取 document.writeln() 内容,还是您在将页面提供给用户时已经生成该内容?因为如果是前者,我认为您没有理由不能在您使用的任何服务器端技术的会话中保存任何变量/查询,然后从中生成纯文本内容。否则,您将不得不遵循上面的航行者的建议。

Is your javascript AJAX which fetches the document.writeln() content from the server, or are you already generating that content when the page is served to the user ? Because if it's the former, I see no reason why you can't save any variables / queries in the session of whatever server-side technology your using and then just generate the plain text stuff from those. Otherwise, you'll have to folow voyager's suggestion above.

回忆凄美了谁 2024-08-13 09:37:39

既然您使用的是 Ext JS,您可能有一个向网格提供数据的 Store 对象?您应该能够通过浏览商店来提取所需的数据,然后按照您想要的方式对其进行格式化。我认为从生成的 HTML 中抓取数据并不理想。

一旦您从网格中获取所需的数据并将其格式化为文本,您可以将其发布到后端以启动下载(使用内容处置:附件等)。

如果您不关心跨浏览器,您可以还可以使用 data: URL 方案来启动下载,而不涉及后端。

Since you're using Ext JS, you probably have a Store object that provides data to the grid? You should be able to extract the data you need by walking through the Store, and then format it the way you want. I don't think scraping the data from the generated HTML is ideal.

Once you grab the data you need from the grid and format it into text, you could POST it to the backend to initiate a download (with Content-Disposition: attachment etc.)

If you're not concerned with being cross-browser, you can also use the data: URL scheme to initiate a download without involving the backend.

故事灯 2024-08-13 09:37:39

这个插件可以完成这项工作。在 IE、FF 和 IE 上测试铬合金。
https://github.com/dcneiner/Downloadify

This plugin does the job. Tested on IE, FF & Chrome.
https://github.com/dcneiner/Downloadify

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文