jsp输出word
在页面直接打开word。
在Action中写
response.reset();
response.setContentType("application/msword;charset=utf-8");
response.setHeader("Content-Disposition", "inline;filename=temp.doc");
response.getOutputStream().write(document.getContent());
response.getOutputStream().flush();
response.getOutputStream().close();
return null;
在页面时下载word。
在Action中写
response.reset();
response.setContentType("application/x-download;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=temp.doc");
response.getOutputStream().write(document.getContent());
response.getOutputStream().flush();
response.getOutputStream().close();
return null;
请问怎么从数据库读取word显示在JSP页面上
还是给你个例子来的比较实际,sql操作台二进制数据
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.sql.*,java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*"%>
<html>
<body>
<%
/*
drop table imagetable;
create table imagetable
(
id int not null,
image image,
primary key (id)
)
*/
/*
//================ 一 、将文件写入到数据库的大字段中begin=====================
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url ="jdbc:microsoft:sqlserver://127.0.0.1:1433;DataBaseName=zl";
Connection conn= DriverManager.getConnection(url,"sa","1234");
File file = new File("e:/1.jpg");
FileInputStream is=new FileInputStream(file);
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO imagetable (id,image)" + "VALUES (?, ?)");
stmt.setInt(1, 1);
stmt.setBinaryStream(2, is,(int)file.length());
stmt.executeUpdate();
stmt.close();
is.close();
out.println("恭喜你,你成功加入一张图片!");
//===============将文件写入到数据库的大字段中end=========================
*/
/*
//====================== 二、jsp显示服务器硬盘图片示例 begin==============
FileInputStream is=new FileInputStream("e:/1.jpg");
response.reset();
response.setContentType("image/jpeg");
ServletOutputStream sos = response.getOutputStream();
byte[] buffer = new byte[1024];
int len=0;
while((len=is.read(buffer))>0){
sos.write(buffer,0,len);
}
sos.flush();
sos.close();
//=======================jsp显示服务器硬盘图片示例 end===================
*/
//===================== 三、将数据库的大字段图片还原到本地,并在网页上显示begin==============
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost:3306/test?user=root&password=eastsoftweb";
Connection conn= DriverManager.getConnection(url);
java.io.File file = new File("d:/temp/db.jpg");
FileOutputStream os=new FileOutputStream(file);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs=stmt.executeQuery("select nid,image from imagetable where nid=1");
rs.next();
byte[] buffer=rs.getBytes(2);
stmt.close();
os.write(buffer);
os.flush();
os.close();
out.println("query end");
//网页上显示
response.reset();
response.setContentType("image/jpeg");
ServletOutputStream sos = response.getOutputStream();
sos.write(buffer);
sos.flush();
sos.close();
//======================将数据库的大字段图片还原到本地,并在网页上显示end===================
/*
//======================四、生成缩略图begin==============================
File file = new File("d:/temp/1.JPG");
String newurl="d:/temp/2.jpg"; //新的缩略图保存地址
Image src = javax.imageio.ImageIO.read(file); //构造Image对象
float tagsize=200;
int old_w=src.getWidth(null); //得到源图宽
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0; //得到源图长
int tempsize;
float tempdouble;
if(old_w>old_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
new_w=Math.round(old_w/tempdouble);
new_h=Math.round(old_h/tempdouble);//计算新图长宽
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG编码
newimage.close();
//========================生成缩略图end================================
*/
%>
如何将JSP从数据库读出的表格保存到本地word文件,求教大神
将带有格式的文本保存到数据库中的方法/步骤:
1、在jsp中,页面的带有格式的文本内容外面用一个大的标签,给定表签名。
2、页面做提交的时候用上面的表签名点innerHTML的方式来获取页面带有标签和样式的内容。
3、将上面取得的内容作为一个字符串保存到数据库即可,下次把数据库里的内容直接输出到页面就可以了。
对于要输出到word里保存样式的方法也是类似的,只是需要去看一下word解析文本的方式与jsp有何区别,在输出到word的时候做一下变换即可。
jsp有办法实现word/excel的在线预览吗
1.jsp页面
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data">
<!-- name为后台对应的参数名称 -->
<s:file name="files" label="file1"></s:file>
<s:file name="files" label="file2"></s:file>
<s:file name="files" label="file3"></s:file>
<s:submit value="提交" id="submitBut"></s:submit>
</s:form>
2.Action
//单个文件上传可以用 File files,String filesFileName,String filesContentType
//名称要与jsp中的name相同(三个变量都要生成get,set)
private File[] files;
// 要以File[]变量名开头
private String[] filesFileName;
// 要以File[]变量名开头
private String[] filesContentType;
private ServletContext servletContext;
//Action调用的上传文件方法
public String execute() {
ServletContext servletContext = ServletActionContext.getServletContext();
String dataDir = servletContext.getRealPath("/file/upload");
System.out.println(dataDir);
for (int i = 0; i < files.length; i++) {
File saveFile = new File(dataDir, filesFileName[i]);
files[i].renameTo(saveFile);
}
return "success";
}
3.配置上传文件临时文件夹(在struts.xml中配置)
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下载
1.下载的url(到Action)
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下载</a>
2.struts.xml配置
<package name="file" namespace="/file" extends="struts-default">
<action name="fileAction" class="com.struts2.file.FileAction">
<!-- 下载文件配置 -->
<!--type 为 stream 应用 StreamResult 处理-->
<result name="down" type="stream">
<!--
不管实际类型,待下载文件 ContentType 统一指定为 application/octet-stream
默认为 text/plain
-->
<param name="contentType">application/octet-stream</param>
<!--
默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,
比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法
-->
<param name="inputName">inputStream</param>
<!--
默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文
件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,
这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名
-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 输出时缓冲区的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
3.Action
//Action调用的下载文件方法
public String down() {
return "down";
}
//获得下载文件的内容,可以直接读入一个物理文件或从数据库中获取内容
public InputStream getInputStream() throws Exception {
String dir = servletContext.getRealPath("/file/upload");
File file = new File(dir, "icon.png");
if (file.exists()) {
//下载文件
return new FileInputStream(file);
//和 Servlet 中不一样,这里我们不需对输出的中文转码为 ISO8859-1
//将内容(Struts2 文件下载测试)直接写入文件,下载的文件名必须是文本(txt)类型
//return new ByteArrayInputStream("Struts2 文件下载测试".getBytes());
}
return null;
}
// 对于配置中的 ${fileName}, 获得下载保存时的文件名
public String getFileName() {
String fileName ="图标.png";
try {
// 中文文件名也是需要转码为 ISO8859-1,否则乱码
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "icon.png";
}
}
将JSP页面(里面含有表格,表格数据是从数据库导出的)导出成Word
用最新版本的POI是支持到word2007的,如果你尝试后还不行,给我留言,我给你word2007的全套解析,你可以尝试自己写一套解析代码出来。
大神,跪求你的QQ啊……
如何将jsp页面转化成word文档打印出来
可以利用table把试卷输出,然后利用JavaScript保存此表格为Word文档。
//下面代码为引用论坛其他人的回复,自己没测试过
App为表格ID,你调用一下SaveAs函数.
function PrintFile()
{
var strResult=window.confirm("确认用Word打印吗?");
if(strResult)
{
try
{
App.focus();
document.execCommand("SelectAll");
document.execCommand("Copy");
App.focus();
var WordApp=new ActiveXObject("Word.Application");
WordApp.Application.Visible=true;
var Doc=WordApp.Documents.Add();
Doc.Activate();
Doc.Content.Paste();
Doc.PrintPreview();
WordApp.DisplayAlerts=false;
Doc.Close();
WordApp.DisplayAlerts=true;
WordApp.Quit();
}
catch(e){}
}
else
{
var hwnd=window.open("");
hwnd.document.write(App.innerHTML);
}
return false;
}
关于jsp用EL输出的问题
<c:out value="${results.content}" escapeXml="false"></c:out>
${results.content}
<bean:write name="results" property="content" filter="false"/>
怎样将用struts2 jsp 将word文档展现在网页上,而且不需要选在是否保存 下载
一、把jsp页面数据复制到word文档
var table=document.getElementByIdx_x('printTable');
row=table.rows.length;
column=table.rows(1).cells.length;
var word = new ActiveXObject("Word.Application");
word.Application.Visible = true;
word.Selection.Text ="<%=reportTitle%>";
var mydoc=word.Documents.Add('',0,0);
myRange =mydoc.Range(0,1);
var sel=document.body.createTextRange();
sel.moveToElementText(table);
sel.select();
sel.execCommand('Copy');
myRange.Paste();
二、把jsp页面数据写入word文档
var table=document.getElementByIdx_x('printTable');
row=table.rows.length;
column=table.rows(1).cells.length;
var wdapp=new ActiveXObject("Word.Application");
wdapp.visible=true;
wddoc=wdapp.Documents.Add(); //添加新的文档
thearray=new Array();
//将页面中表格的内容存放在数组中
for(i=0;i<row;i ){
thearray[i]=new Array();
for(j=0;j<column;j ){
thearray[i][j]=table.rows(i).cells(j).innerHTML;
}
}
var range = wddoc.Range(0,0);
range.Text="<%=reportTitle%>" " ";
wdapp.Application.Activedocument.Paragraphs.Add(range);
wdapp.Application.Activedocument.Paragraphs.Add();
rngcurrent=wdapp.Application.Activedocument.Paragraphs(3).Range;
var objTable=wddoc.Tables.Add(rngcurrent,row,column) //插入表格
for(i=0;i<row;i ){
for(j=0;j<column;j ){
objTable.Cell(i 1,j 1).Range.Text = thearray[i][j].replace("","");
}
}
三jsp生成word,excle,pdf
在web-oa系统中,公文管理好象不可或缺,有时需要从数据库中查询一些数据以某种格式输出来,并以word文档的形式展现,有时许多word文档保存到数据库中的某个表的Blob字段里,服务器再把保存在Blob字段中的图片文件展现给用户。通过网上查找发现很少有关于此类的文章,现在整理起来供大家参考。
1 在client端直接生成word文档
在jsp页面上生成word文档非常简单,只需把contentType=”text/html”改为contentType="application/msword; charset=utf-8"即可,代码如下:
通过设置可以使原来页面的内容在word中表现出来。
如果需要把word文档下载下来,只需在jsp页面上面加上如下代码:
其中filename.doc中filename是要下载的word文档的文件名,可以通过来自行定制,如下
.doc");
%>
这样提供一个提示信息供用户选择如下图所示
小技巧:如果程序员需要在生成word文档的时候按照自己预先在word上设计好的格式,可以复制word格式然后粘贴到frontpage中,取html代码贴到jsp页面即可。
2 在客户端输出存在数据库中的word实体
这里只讨论在client输出oracle中BLOB字段中的word文档实体。其中调用了类getBlobBean,该类提供了从oracle中取出blob功能,代码如下:
package yourpackage;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import oracle.sql.*;
import beans.yourbeanpackage. getBlobBean;
public class GetBlobServlet1 extends HttpServlet {
//设置输出内容类型,这个设置很重要,否则客户端浏览器不能识别输出内容,导致弹出下载的对话框。
private static final String CONTENT_TYPE = "application/msword;charset=utf-8";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
perform(request,response);
}
public void perform(HttpServletRequest request, HttpServletResponse response){
try{
//该类功能是从oracle哭中取出blob实体
getBlobBean getBlob=new getBlobBean();
OutputStream sos = response.getOutputStream();
getBlob.connFunction();
oracle.sql.BLOB blob=getBlob.getBlob("cehui");
//输出word文档
if(blob!=null){
InputStream pi = blob.getBinaryStream();
int blobsize =(int)blob.length();
byte[] blobbytes = new byte[blobsize];
int bytesRead = 0;
while ((bytesRead = pi.read(blobbytes)) != -1) {
sos.write(blobbytes, 0, bytesRead);
}
pi.close();
sos.flush();
sos.close();
}
getBlob.dropConnFunction();
}catch(Exception e){
System.out.println(e.toString());
}
}
//Clean up resources
public void destroy() {
}
}
3 在client端直接生成EXCEL文档
生成例子excel 。 用WORD排版面,倒出HTML 把代码拷贝到网页里,然后这个JSP页面打印你就随心所欲的控制了。
4 在client端直接生成PDF文档
需要下载JAR包:以下代码在JDK1.4 RESIN2.16 下测试通过
ITEXT包 http://mesh.dl.sourceforge.net/sourceforge/itext/itext-1.3.5.jar
字体包http://itext.sourceforge.net/downloads/iTextAsian.jar
JSP生成到客户IE端直接打开
ie_PDF.jsp
-------------------------------
在服务器端生成不下载。
server_PDF.jsp
使用iText可以设置文字的字体,对于我们中国的程序员来说如何显示中文是最紧要的问题。幸好iText中有一个专门的包用来设置亚洲国家的字体你可以从http://itext.sourceforge.net/downloads/iTextAsian.jar下载这个包。然后把它直接放到你的ClassPath中就可以了。如何设置字体呢?
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
在上面的代码中设置了中文字体的显示,你只要使用下面的代码就可以包中文加到PDF中了
String title = "我爱喝咖啡";
Paragraph t = new Paragraph(title, FontChinese);
doc.add(t);
转载请注明出处51数据库 » jspword输出图片 jsp导出到word
猴子出身