excel工具类
package com.ohd.ie.proct.action;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import org.apache.commons.io.output.ByteArrayOutputStream;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
public class Excel {
private OutputStream os;
private WritableWorkbook wwb = null;
private WritableSheet ws = null;
private WritableCellFormat titleCellFormat = null;
private WritableCellFormat noBorderCellFormat = null;
private WritableCellFormat hasBorderCellFormat = null;
private WritableCellFormat hasBorderCellNumberFormat = null;
private WritableCellFormat hasBorderCellNumberFormat2 = null;
private WritableImage writableImage=null;
private int r;
public Excel(OutputStream os){
this.os = os;
r = -1;
try {
wwb = Workbook.createWorkbook(os);
//创建工作表
ws = wwb.createSheet("sheet1",0);
//设置表头字体,大小,加粗
titleCellFormat = new WritableCellFormat();
titleCellFormat.setAlignment(Alignment.CENTRE);
titleCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
//自动换行
titleCellFormat.setWrap(true);
titleCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12,WritableFont.BOLD));
titleCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//设置表格字体,大小----无边框
noBorderCellFormat = new WritableCellFormat();
noBorderCellFormat.setAlignment(Alignment.CENTRE);
noBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
noBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
//设置表格字体,大小----有边框
hasBorderCellFormat = new WritableCellFormat();
hasBorderCellFormat.setAlignment(Alignment.CENTRE);
hasBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
hasBorderCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//设置表格字体,大小----有边框(小数)
NumberFormat nf = new NumberFormat("#0.00");
hasBorderCellNumberFormat = new WritableCellFormat(nf);
hasBorderCellNumberFormat.setAlignment(Alignment.CENTRE);
hasBorderCellNumberFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellNumberFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
hasBorderCellNumberFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//设置表格字体,大小----有边框(整数)
NumberFormat nf2 = new NumberFormat("#0");
hasBorderCellNumberFormat2 = new WritableCellFormat(nf2);
hasBorderCellNumberFormat2.setAlignment(Alignment.CENTRE);
hasBorderCellNumberFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellNumberFormat2.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
hasBorderCellNumberFormat2.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param content 内容
* @param c 列
* @param style 样式
* @param isNewLine 是否换行
* @param mergeType 合并类型
* @param mergeCount 合并个数
* @param width 单元格宽
*/
public void setExcelCell(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width){
try {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////报表内容////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
if(isNewLine){
r++;
}
WritableCell l = null;
if(style == 1){
l = new Label(c,r,content,titleCellFormat);
}
else if(style == 2){
l = new Label(c,r,content,noBorderCellFormat);
}
else if(style == 3){
l = new Label(c,r,content,hasBorderCellFormat);
}
else if(style == 4){
l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);
}
else if(style == 5){
l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);
}
ws.addCell(l);
if(width != 0){
ws.setColumnView(c,width);
}
//veryhuo,com
if(mergeType == 1){
//x 轴方向
ws.mergeCells(c, r, c+mergeCount-1 , r);
}
else if(mergeType == 2){
//y 轴方向
ws.mergeCells(c, r, c, r+mergeCount-1);
}
if(isNewLine){
ws.setRowView(r, 350);
if(style == 1 && r != 0){
ws.setRowView(r, 900);
}
else{
ws.setRowView(r, 350);
}
}
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void setExcelCellEx(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width,int row){
try {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////报表内容////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
if(isNewLine){
r++;
}
WritableCell l = null;
if(style == 1){
l = new Label(c,r,content,titleCellFormat);
}
else if(style == 2){
l = new Label(c,r,content,noBorderCellFormat);
}
else if(style == 3){
if(content.indexOf(".jpg")!=-1 ||content.indexOf(".JPG")!=-1){
File outputFile=null;
File imgFile =new File(content);
if(imgFile.exists()&&imgFile.length()>0){
BufferedImage input=null;
try {
input = ImageIO.read(imgFile);
} catch (Exception e) {
e.printStackTrace();
}
if(input!=null){
String path=imgFile.getAbsolutePath();
outputFile = new File(path.substring(0,path.lastIndexOf('.')+1)+"png");
ImageIO.write(input, "PNG", outputFile);
if(outputFile.exists()&&outputFile.length()>0){
ws.setRowView(row,2000);
//ws.setColumnView(8, 10);
writableImage = new WritableImage(c+0.1, row+0.1, 0.8, 0.8, outputFile);
ws.addImage(writableImage);
l = new Label(c,r,"",hasBorderCellFormat);
}
}
}
}else{
l = new Label(c,r,content,hasBorderCellFormat);
}
}
else if(style == 4){
l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);
}
else if(style == 5){
l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);
}
ws.addCell(l);
if(width != 0){
ws.setColumnView(c,width);
}
if(mergeType == 1){
//x 轴方向
ws.mergeCells(c, r, c+mergeCount-1 , r);
}
else if(mergeType == 2){
//y 轴方向
ws.mergeCells(c, r, c, r+mergeCount-1);
}
if(isNewLine){
ws.setRowView(r, 350);
if(style == 1 && r != 0){
ws.setRowView(r, 900);
}
else{
ws.setRowView(r, 350);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void setRowHeight(int val){
try {
ws.setRowView(r, val);
} catch (RowsExceededException e) {
e.printStackTrace();
}
}
public void getExcelResult(){
try {
wwb.write();
} catch (Exception e) {
System.out.println(e.toString());
}
finally{
if(wwb != null){
try {
wwb.close();
if(os != null){
os.close();
}
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
需要的jar包:jxl.jar
Ⅱ 如何用JAVA导出Excel(使用POI)
response.setContentType("bin");
response.setHeader("Content-disposition","attachment;filename=test.xls");
你在servlet里面设置响应头为这样,然后就能够实现下载了,然后使用输出流进行输出下载
.....还有问题的话就问..
你要是想全部代码都写的话..加我扣扣 1195391953..
Ⅲ 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
*@N
*
*/
{
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
Ⅳ 如何导出生成excel文件 java
在编程中经常需要使用到表格(报表)的处理主要以Excel表格为主。下面给出用java写入数据到excel表格方法:
1.添加jar文件
java导入导出Excel文件要引入jxl.jar包,最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。下载地址:http://www.andykhan.com/jexcelapi/
2.jxl对Excel表格的认识
可以参见http://www.cnblogs.com/xudong-bupt/archive/2013/03/19/2969997.html
3.java代码根据程序中的数据生成上述图片所示的t.xls文件
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.io.File;
import jxl.*;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Writer_excel{
public static void main(String[] args) {
//标题行
String title[]={"角色","编号","功能名称","功能描述"};
//内容
String context[][]={{"UC11","设置课程","创建课程"},
{"UC12","设置学生名单","给出与课程关联的学生名单"},
{"UC21","查看学生名单",""},
{"UC22","查看小组信息","显示助教所负责的小组列表信息"}
};
//操作执行
try {
//t.xls为要新建的文件名
WritableWorkbook book= Workbook.createWorkbook(new File("t.xls"));
//生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet=book.createSheet("第一页",0);
//写入内容
for(int i=0;i<4;i++) //title
sheet.addCell(new Label(i,0,title[i]));
for(int i=0;i<4;i++) //context
{
for(int j=0;j<3;j++)
{
sheet.addCell(new Label(j+1,i+1,context[i][j]));
}
}
sheet.addCell(new Label(0,1,"教师"));
sheet.addCell(new Label(0,3,"助教"));
/*合并单元格.合并既可以是横向的,也可以是纵向的
*WritableSheet.mergeCells(int m,int n,int p,int q); 表示由(m,n)到(p,q)的单元格组成的矩形区域合并
* */
sheet.mergeCells(0,1,0,2);
sheet.mergeCells(0,3,0,4);
//写入数据
book.write();
//关闭文件
book.close();
}
catch(Exception e) { }
}
Ⅳ 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
/**
*@authorliuwu
* Excel的导入与导出
*/
@SuppressWarnings({"unchecked"})
publicclassExcelOperate{
/**
*@authorliuwu
*这是一个通用的方法,利用了JAVA的反射机制,
*可以将放置在JAVA集合中并且符合一定条件的数据以EXCEL的形式输出到指定IO设备上
*@paramtitle表格标题名
*@paramheaders表格属性列名数组
*@paramdataset需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
* 此方法支持的javabean属性【数据类型有java基本数据类型及String,Date,byte[](图片转成字节码)】
*@paramout与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
*@parampattern如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*@throwsIOException
*/
publicstaticvoidexportExcel(Stringtitle,String[]headers,Collection<?>dataset,OutputStreamout,Stringpattern)throwsIOException{
//声明一个工作薄
HSSFWorkbookworkbook=newHSSFWorkbook();
//生成一个表格
HSSFSheetsheet=workbook.createSheet(title);
//设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short)20);
//生成一个样式
HSSFCellStylestyle=workbook.createCellStyle();
//设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成一个字体
HSSFFontfont=workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short)12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//把字体应用到当前的样式
style.setFont(font);
//生成并设置另一个样式
HSSFCellStylestyle2=workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//生成另一个字体
HSSFFontfont2=workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//把字体应用到当前的样式
style2.setFont(font2);
//产生表格标题行
HSSFRowrow=sheet.createRow(0);
for(shorti=0;i<headers.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextStringtext=newHSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍历集合数据,产生数据行
Iterator<?>it=dataset.iterator();
intindex=0;
while(it.hasNext()){
index++;
row=sheet.createRow(index);
Objectt=it.next();
//利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[]fields=t.getClass().getDeclaredFields();
for(shorti=0;i<fields.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style2);
Fieldfield=fields[i];
StringfieldName=field.getName();
StringgetMethodName="get"
+fieldName.substring(0,1).toUpperCase()
+fieldName.substring(1);//注意实体getSet不要自己改名字不然反射会有问题
try{
ClasstCls=t.getClass();
MethodgetMethod=tCls.getMethod(getMethodName,newClass[]{});
Objectvalue=getMethod.invoke(t,newObject[]{});
HSSFRichTextStringrichString=newHSSFRichTextString(value.toString());
HSSFFontfont3=workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}catch(SecurityExceptione){
e.printStackTrace();
e=null;
}catch(NoSuchMethodExceptione){
e.printStackTrace();
e=null;
}catch(IllegalArgumentExceptione){
e.printStackTrace();
e=null;
}catch(IllegalAccessExceptione){
e.printStackTrace();
e=null;
}catch(InvocationTargetExceptione){
e.printStackTrace();
e=null;
}finally{
//清理资源
}
}
}
try{
workbook.write(out);
}catch(IOExceptione){
e.printStackTrace();
e=null;
}
}
}
Ⅶ java导出excel
wb = Workbook.getWorkbook(file);//按路径获取抄excel表
Sheet sheet = wb.getSheet(0);//第一个工作簿
sheet.getCell(x,y).getContents())//获取x列y行的数据;
需要一个jxl架包
Ⅷ java : 一个excel文件以二进制的形式存在数据库中 如何将它导出并下载到本地
从数据库中得到Blob/Clob,然后得到InputStream,直接给response.getOutputStream() 输出就可以