❶ java怎么导出excel表格
可以使用POI开源的api:
1.首先下载poi-3.6-20091214.jar,下载地址如下:
http://download.csdn.net/detail/evangel_z/3895051
2.Student.java
import java.util.Date;
public class Student
{
private int id;
private String name;
private int age;
private Date birth;
public Student()
{
}
public Student(int id, String name, int age, Date birth)
{
this.id = id;
this.name = name;
this.age = age;
this.birth = birth;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public Date getBirth()
{
return birth;
}
public void setBirth(Date birth)
{
this.birth = birth;
}
}
3.CreateSimpleExcelToDisk.java
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CreateSimpleExcelToDisk
{
/**
* @功能:手工构建一个简单格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Student user1 = new Student(1, "张三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
public static void main(String[] args) throws Exception
{
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("学生表一");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("学号");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("年龄");
cell.setCellStyle(style);
cell = row.createCell((short) 3);
cell.setCellValue("生日");
cell.setCellStyle(style);
// 第五步,写入实体数据 实际应用中这些数据从数据库得到,
List list = CreateSimpleExcelToDisk.getStudent();
for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,创建单元格,并设置值
row.createCell((short) 0).setCellValue((double) stu.getId());
row.createCell((short) 1).setCellValue(stu.getName());
row.createCell((short) 2).setCellValue((double) stu.getAge());
cell = row.createCell((short) 3);
cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
.getBirth()));
}
// 第六步,将文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/students.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
❷ java如何另存导出Excel
1./**
* 出险信息导出到excel(fc)
* @param mapping
* @param form
* @param request
* @param response
* @throws IOException
*/
public void exportActoExcel(ActionMapping mapping, ActionForm form ,
HttpServletRequest request,HttpServletResponse response) throws IOException {
ActionErrors errors = new ActionErrors();
AcExcelBusi acBusi = new AcExcelBusi();
AccidentRecordForm arForm= (AccidentRecordForm) form;
AccidentRecordBusi arBusi = new AccidentRecordBusi();
// ////查询条件
FwUsers sessUser = (FwUsers)request.getSession().getAttribute(ConstValues.SESS_USER_MANAGE);
Map<String,Object> cisMap = arBusi.getTodoPageList(arForm,sessUser,errors);
List AcList = null;// 当页的记录
if (null != cisMap) {
AcList = (List) cisMap.get("list");
}
//导出excel的路径、文件名
String uuid = UUID.create("exp");
String path = request.getSession().getServletContext().getRealPath("/") + ConstValues.EXP_PATH_EXCEL + uuid + ".xls";
acBusi.exprotAcExcel(AcList, path,request);
response.sendRedirect("stdownload.jsp?path=" + path );
}
❸ java如何实现从服务器下载已经生成好的excel文件
使用 HttpURLConnection 去下载 ,按二进制保存文件 ~~~~~~~~~
❹ java 将页面内容写入excel文件中并可以将其下载到本地任意位置
java本身要生成excel文件必然是在后台做的,通过poi库生成excel文件并制作表格。
无法直接通过网页保存生成excel。
至于下载到本地任意位置,也是后台生成了excel文件发送到前台(浏览器),由用户选择要存在哪儿,不能直接存储(这是web沙箱限制,不允许网页直接访问本地硬盘,不然你想想,如果你打开一个网页,网页代码可以任意访问你的硬盘,你还敢开网页吗)。
要绕过沙箱限制必须装插件,也就是,你必须开发一个com或plugin插件,可以访问本地硬盘,但这需要用户手工安装(比如flash的插件,你之所以能用网页看flash是因为装了它的插件,但这是你手工装的,它不能绕过你直接给你装,它必须询问你行不行,你要手工点了OK,才能装)
❺ java如何将导出的excel下载到客户端
packagecom.mr;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.ServletOutputStream;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*利用Servlet导出Excel
*@authorCHUNBIN
*
*/
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("UTF-8");//设置request的编码方式,防止中文乱码
StringfileName="导出数据";//设置导出的文件名称
StringBuffersb=newStringBuffer(request.getParameter("tableInfo"));//将表格信息放入内存
StringcontentType="application/vnd.ms-excel";//定义导出文件的格式的字符串
StringrecommendedName=newString(fileName.getBytes(),"iso_8859_1");//设置文件名称的编码格式
response.setContentType(contentType);//设置导出文件格式
response.setHeader("Content-Disposition","attachment;filename="+recommendedName+""");//
response.resetBuffer();
//利用输出输入流导出文件
ServletOutputStreamsos=response.getOutputStream();
sos.write(sb.toString().getBytes());
sos.flush();
sos.close();
}
}
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>导出Excel</title>
<scripttype="text/javascript">
functiontest(){
document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;
}
</script>
<style>
body{font-family:宋体;font-size:11pt}
</style>
</head>
<body>
<formaction="<%=request.getContextPath()%>/servlet/ExportExcelServlet"method="post">
<spanid="table">
<tablebgcolor="#EEECF2"bordercolor="#A3B2CC"border="1"cellspacing="0">
<tr><th>学号</th><th>姓名</th><th>科目</th><th>分数</th></tr>
<tr><td>10001</td><td>赵二</td><td>高数</td><td>82</td></tr>
<tr><td>10002</td><td>张三</td><td>高数</td><td>94</td></tr>
<tr><td>10001</td><td>赵二</td><td>线数</td><td>77</td></tr>
<tr><td>10002</td><td>张三</td><td>线数</td><td>61</td></tr>
</table>
</span><br/>
<inputtype="submit"name="Excel"value="导出表格"onclick="test()"/>
<inputtype="hidden"id="tableInfo"name="tableInfo"value=""/>
</form>
</body>
</html>
以上代码来自网络:http://jtlyuan.iteye.com/blog/1322097
❻ java导出excel
public String downModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/") + "doc/";
String fileName = request.getParameter("fileName") == null ? "" : request.getParameter(
"fileName").trim();
String downLoadPath = ctxPath + fileName;
try {
long fileLength = new File(downLoadPath).length();
/*response.setHeader("Content-disposition", "attachment; filename="
+ new String(fileName.getBytes("utf-8"), "ISO8859-1")); */
String agent= request.getHeader("USER-AGENT");System.out.println(agent);
if (null != agent && -1 != agent.indexOf("MSIE")) {
response.addHeader("Content-Disposition","attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", " ") + "\"");
} else if (null != agent && -1 != agent.indexOf("Firefox")) {
response.addHeader("Content-Disposition","attachment; filename=\"" + new String(fileName.getBytes(), "iso8859-1") + "\"");
}else{
response.setHeader("Content-Disposition","attachment;filename="+new String(java.net.URLEncoder.encode(fileName,"utf-8").getBytes(),"iso8859-1"));
}
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
差不多是这样,点击按钮时候走这个方法, path 跟 name那块需要根据你自己的情况改下。
❼ java web项目: 一个excel文件以二进制的形式存在数据库中 如何将它导出并
poi读取即可。
/**
* 读取Excel数据内容
* @param InputStream
* @return Map 包含单元格数据内容的Map对象
*/
public Map<Integer, String> readExcelContent(InputStream is) {
Map<Integer, String> content = new HashMap<Integer, String>();
String str = "";
try {
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
while (j < colNum) {
// 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据
// 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
// str += getStringCellValue(row.getCell((short) j)).trim() +
// "-";
str += getCellFormatValue(row.getCell((short) j)).trim() + " ";
j++;
}
content.put(i, str);
str = "";
}
return content;
}
❽ Java导出execl并下载
struts2 Action的类中代码
public void createExecl() throws WriteException, IOException{
WritableWorkbook book=null;
@SuppressWarnings("unused")
WritableSheet sheet=null;
try{
String path="C:\\test.xls";
File file=new File(path);
//打开文件
book = Workbook.createWorkbook(file);
// 生成名为“第一页”的工作表,参数0表示这是第一页
sheet = book.createSheet( " 第一页 " , 0 );
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
}catch(Exception e){
System.out.println(e);
}finally{
//写入数据并关闭文件
book.write();
book.close();
}
try {
String path="C:\\test.xls";
File file=new File(path);
// Excel获得文件
Workbook wb = Workbook.getWorkbook(file);
// 打开一个文件的副本,并且指定数据写回到原文件
WritableWorkbook book2 = Workbook.createWorkbook(file, wb);
// 添加一个工作表
//WritableSheet sheet = book.createSheet( " 第二页 " , 1 );
//WritableSheet sheet = book.getSheet(0);
WritableSheet sheet2=book2.getSheet(0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
// 以及单元格内容为test
Label label=null;
Label label2=null;
label=new Label(0,0,"计费Id");
sheet2.addCell(label);
label=new Label(1,0,"主动呼叫号码");
sheet2.addCell(label);
label=new Label(2,0,"被动呼叫号码");
sheet2.addCell(label);
label=new Label(3,0,"计费开始时间");
sheet2.addCell(label);
label=new Label(4,0,"计费结束时间");
sheet2.addCell(label);
label=new Label(5,0,"计费单价");
sheet2.addCell(label);
label=new Label(6,0,"计费总金额");
sheet2.addCell(label);
label=new Label(7,0,"扣费号码");
sheet2.addCell(label);
label=new Label(8,0,"活动名称");
sheet2.addCell(label);
label=new Label(9,0,"备注");
sheet2.addCell(label);
int j=1;
List<Object> list=baseManager.findByHql("from TalkInformationBean tb left join fetch tb.activeBean order by tb.talkId desc tb.talkId");
Iterator<Object> it=list.iterator();
while(it.hasNext()){
talkInfo=(TalkInformationBean)it.next();
label2 = new Label( 0 , j , talkInfo.getTalkId().toString() );
sheet2.addCell(label2);
label2 = new Label( 1 , j , talkInfo.getInitiMobile().toString() );
sheet2.addCell(label2);
label2 = new Label( 2 , j , talkInfo.getPassMobile().toString() );
sheet2.addCell(label2);
label2 = new Label( 3 , j , talkInfo.getStartTime().toString() );
sheet2.addCell(label2);
label2 = new Label( 4 , j , talkInfo.getEndTime().toString() );
sheet2.addCell(label2);
label2 = new Label( 5 , j , talkInfo.getPrice().toString() );
sheet2.addCell(label2);
label2 = new Label( 6 , j , talkInfo.getTotalMoney().toString() );
sheet2.addCell(label2);
label2 = new Label( 7 , j , talkInfo.getDectMobile().toString() );
sheet2.addCell(label2);
if(talkInfo.getActiveBean()==null){
label2 = new Label( 8 , j , null);
}else{
label2 = new Label( 8 , j , talkInfo.getActiveBean().getActiveName().toString());
}
sheet2.addCell(label2);
label2 = new Label( 9 , j , talkInfo.getRemark().toString() );
sheet2.addCell(label2);
j++;
}
// 将定义好的单元格添加到工作表中
book2.write();
book2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public InputStream getDownloadFile() {
File file = new File("C:\\test.xls");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return fis;
}
/**
* 查询所有通话记录
*
* @param
*
* @return
* String success --> 欢迎页面 fail --> 错误页面
* @throws IOException
* @throws WriteException
* @throws
* HRException
*/
@SuppressWarnings("unchecked")
public String toexport() throws WriteException, IOException{
this.createExecl();
return "success";
}
struts.xml代码
<action name="toexport" class="talkAction" method="toexport">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="test.xls"</param>
<param name="inputName">downloadFile</param>
</result>
<result name="TALKINFO">/talkInfo/talkInfo.jsp</result>
</action>
JSP页面代码
<input class="input_back" type="button" name="Submit0" value="导出数据"onclick="location.href='toexport.action'"/></td>
❾ java : 一个excel文件以二进制的形式存在数据库中 如何将它导出并下载到本地
从数据库中得到Blob/Clob,然后得到InputStream,直接给response.getOutputStream() 输出就可以