❶ 在java编程中怎么将从数据库查询出来的数据导成Excel文件
import jxl.*; x0dx0aimport jxl.write.*; x0dx0aimport java.io.*; x0dx0aimport java.io.File.*; x0dx0aimport java.util.*; x0dx0ax0dx0apublic class excel x0dx0a{ x0dx0apublic static void main(String[] args) x0dx0a{ x0dx0ax0dx0aString targetfile = "c:/out.xls";//输出的excel文件名 x0dx0aString worksheet = "List";//输出的excel文件工作表名 x0dx0aString[] title = {"ID","NAME","DESCRIB"};//excel工作表的标题 x0dx0ax0dx0aWritableWorkbook workbook; x0dx0atry x0dx0a{ x0dx0a//创建可写入的Excel工作薄,运行生成的文件在tomcat/bin下 x0dx0a//workbook = Workbook.createWorkbook(new File("output.xls")); x0dx0aSystem.out.println("begin"); x0dx0ax0dx0aOutputStream os=new FileOutputStream(targetfile); x0dx0aworkbook=Workbook.createWorkbook(os); x0dx0ax0dx0aWritableSheet sheet = workbook.createSheet(worksheet, 0); //添加第一个工作表 x0dx0a//WritableSheet sheet1 = workbook.createSheet("MySheet1", 1); //可添加第二个工作 x0dx0a/* x0dx0ajxl.write.Label label = new jxl.write.Label(0, 2, "A label record"); //put a label in cell A3, Label(column,row) x0dx0asheet.addCell(label); x0dx0a*/ x0dx0ax0dx0ajxl.write.Label label; x0dx0afor (int i=0; i
❷ java端导出Excel表格。
可以使用poi来实现导出execl表格或者通过io流实现导出execl表格,但是poi相对来说更方便
实例如下:
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);
// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}
//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){
Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数
for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
if(j == 0){
cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(i+1);
}else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}
}
cell.setCellStyle(style); //设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}
if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response = getResponse();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
❸ java导出excel
java导出Excel java 代码 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.serv ... java导出Excel例举方式 方法一:导出Excel数据的插件jexcelapi 程序实例如下: public void exportClassroom(OutputStream os) throws PaikeException { try { WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件 WritableSheet wsheet = wbook.createSheet("教室信息表", 0); //工作表名称 //设置Excel字体 WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK); WritableCellFormat titleFormat = new WritableCellFormat(wfont); String[] title = { "教室名", "容 量", "类 型", "其他说明" }; //设置Excel表头 for (int i = 0; i < title.length; i++) { Label excelTitle = new Label(i, 0, title[i], titleFormat); wsheet.addCell(excelTitle); } int c = 1; //用于循环时Excel的行号 ClassroomService cs = new ClassroomService(); List list = cs.findAllClassroom(); //这个是从数据库中取得要导出的数据 Iterator it = list.iterator(); while (it.hasNext()) { ClassroomDTO crdto = (ClassroomDTO) it.next(); Label content1 = new Label(0, c, crdto.getRoomname()); Label content2 = new Label(1, c, crdto.getCapicity().toString()); Label content3 = new Label(2, c, crdto.getRoomTypeId() .toString()); Label content4 = new Label(3, c, crdto.getRemark()); wsheet.addCell(content1); wsheet.addCell(content2); wsheet.addCell(content3); wsheet.addCell(content4); c++; } wbook.write(); //写入文件 wbook.close(); os.close(); } catch (Exception e) { throw new PaikeException("导出文件出错"); } } 方法二:直接用Java代码实现导出Excel报表 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */
❹ 如何导出生成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
java中jxl导出数据到excel的例子
import jxl.*;
import jxl.write.*;
import java.io.*;
import java.io.File.*;
import java.util.*;
public class excel
{
public static void main(String[] args)
{
String targetfile = "c:/out.xls";//输出的excel文件名
String worksheet = "List";//输出的excel文件工作表名
String[] title = {"ID","NAME","DESCRIB"};//excel工作表的标题
WritableWorkbook workbook;
try
{
//创建可写入的Excel工作薄,运行生成的文件在tomcat/bin下
//workbook = Workbook.createWorkbook(new File("output.xls"));
System.out.println("begin");
OutputStream os=new FileOutputStream(targetfile);
workbook=Workbook.createWorkbook(os);
WritableSheet sheet = workbook.createSheet(worksheet, 0); //添加第一个工作表
//WritableSheet sheet1 = workbook.createSheet("MySheet1", 1); //可添加第二个工作
/*
jxl.write.Label label = new jxl.write.Label(0, 2, "A label record"); //put a label in cell A3, Label(column,row)
sheet.addCell(label);
*/
jxl.write.Label label;
for (int i=0; i<title.length; i++)
{
//Label(列号,行号 ,内容 )
label = new jxl.write.Label(i, 0, title[i]); //put the title in row1
sheet.addCell(label);
}
//下列添加的对字体等的设置均调试通过,可作参考用
//添加数字
jxl.write.Number number = new jxl.write.Number(3, 4, 3.14159); //put the number 3.14159 in cell D5
sheet.addCell(number);
//添加带有字型Formatting的对象
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES,10,WritableFont.BOLD,true);
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
jxl.write.Label labelCF = new jxl.write.Label(4,4,"文本",wcfF);
sheet.addCell(labelCF);
//添加带有字体颜色,带背景颜色 Formatting的对象
jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
wcfFC.setBackground(jxl.format.Colour.BLUE);
jxl.write.Label labelCFC = new jxl.write.Label(1,5,"带颜色",wcfFC);
sheet.addCell(labelCFC);
//添加带有formatting的Number对象
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
jxl.write.Number labelNF = new jxl.write.Number(1,1,3.1415926,wcfN);
sheet.addCell(labelNF);
//3.添加Boolean对象
jxl.write.Boolean labelB = new jxl.write.Boolean(0,2,false);
sheet.addCell(labelB);
//4.添加DateTime对象
jxl.write.DateTime labelDT = new jxl.write.DateTime(0,3,new java.util.Date());
sheet.addCell(labelDT);
//添加带有formatting的DateFormat对象
jxl.write.DateFormat df = new jxl.write.DateFormat("ddMMyyyyhh:mm:ss");
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(1,3,new java.util.Date(),wcfDF);
sheet.addCell(labelDTF);
//和宾单元格
//sheet.mergeCells(int col1,int row1,int col2,int row2);//左上角到右下角
sheet.mergeCells(4,5,8,10);//左上角到右下角
wfc = new jxl.write.WritableFont(WritableFont.ARIAL,40,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);
jxl.write.WritableCellFormat wchB = new jxl.write.WritableCellFormat(wfc);
wchB.setAlignment(jxl.format.Alignment.CENTRE);
labelCFC = new jxl.write.Label(4,5,"单元合并",wchB);
sheet.addCell(labelCFC); //
//设置边框
jxl.write.WritableCellFormat wcsB = new jxl.write.WritableCellFormat();
wcsB.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THICK);
labelCFC = new jxl.write.Label(0,6,"边框设置",wcsB);
sheet.addCell(labelCFC);
workbook.write();
workbook.close();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("end");
Runtime r=Runtime.getRuntime();
Process p=null;
//String cmd[]={"notepad","exec.java"};
String cmd[]={"C:\\Program Files\\Microsoft Office\\Office\\EXCEL.EXE","out.xls"};
try{
p=r.exec(cmd);
}
catch(Exception e){
System.out.println("error executing: "+cmd[0]);
}
}
}
❻ java中怎么把报表导出到excel
导入数据库
@RequestMapping("/uploadOrderFile")
@ResponseBody
publicObjectuploadOrderFile(HttpServletRequestrequest,HttpServletResponseresponse,@RequestParam(value="file")MultipartFile[]files)throwsServletException,IOException,ParseException{
Workbookrwb=null;
if(files!=null&&files.length>0){
try{
//StringfilePath=request.getSession().getServletContext().getRealPath("/")+"\uploadOrderFile\"+files.getOriginalFilename();
//System.out.println("----------"+filePath);
rwb=Workbook.getWorkbook(files[0].getInputStream());
Sheetrs=rwb.getSheet(0);//默认0是第一张表,或者rwb.getSheet(Sheet1)Excel要导入的表名
intclos=rs.getColumns();//得到所有的列
introws=rs.getRows();//得到所有的行
//存放Excel表抬头名称以及对应的列
Map<Integer,Object>map=newHashMap<Integer,Object>();
//实体类集合存放每次循环获得的值
List<Medicine>medicineList=newArrayList<Medicine>();
for(inti=0;i<rows;i++){
//创建实体类
Medicinemedicine=newMedicine();
if(i==0){//遍历第一行获取抬头跟对应的列
for(intj=0;j<clos;j++){//取得每个抬头名称对应的列
if(rs.getCell(j,i).getContents().equals("品名")){
map.put(j,"品名");
}elseif(rs.getCell(j,i).getContents().equals("商品编号")){
map.put(j,"商品编号");
}elseif(rs.getCell(j,i).getContents().equals("生产日期")){
map.put(j,"生产日期");
}elseif(rs.getCell(j,i).getContents().equals("产地")){
map.put(j,"产地");
}elseif(rs.getCell(j,i).getContents().equals("生产厂家")){
map.put(j,"生产厂家");
}elseif(rs.getCell(j,i).getContents().equals("批号")){
map.put(j,"批号");
}
}
}else{
//循环遍历map》》》存的Excel表的抬头名称以及对应的列
for(intj=0;j<clos;j++){
if(map.get(j)==null){//如果=null进入下一个循环
continue;
}
if(map.get(j).equals("品名")){
//如果为空结束当前循环,进入下一个循环
if(rs.getCell(j,i).getContents()==null||rs.getCell(j,i).getContents().equals("")){
continue;
}
medicine.setMedicineName(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("商品编号")&&map.get(j)!=null){
//如果为空结束当前循环,进入下一个循环
if(rs.getCell(j,i).getContents()==null||rs.getCell(j,i).getContents().equals("")){
continue;
}
medicine.setMedicineCode(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("生产日期")&&map.get(j)!=null){
medicine.setCreateTime(rs.getCell(j,i).getContents());
if(rs.getCell(j,i).getContents()!=null&&!rs.getCell(j,i).getContents().equals("")){
//如果生产日期存在则+三年给到期日期赋值
//CommonUtil.getMedicineEffectiveTime为封装好的类
medicine.setEffectTime(CommonUtil.getMedicineEffectiveTime(rs.getCell(j,i).getContents(),3));
}
}elseif(map.get(j).equals("产地")&&map.get(j)!=null){
medicine.setAddress(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("生产厂家")&&map.get(j)!=null){
medicine.setProcingArea(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("批号")&&map.get(j)!=null){
medicine.setBatchNumber(rs.getCell(j,i).getContents());
}
}
medicineList.add(medicine);//获得的值放入集合中
}
}
//新增用到的list
List<Medicine>addList=newArrayList<Medicine>();
//修改用到的list
List<Medicine>updateList=newArrayList<Medicine>();
//导入数据
for(inti=0;i<medicineList.size();i++){
//判断商品编号是否存在
if(medicineService.selectMedicineCode(medicineList.get(i).getMedicineCode()).size()>0){
//如果存在则修改
updateList.add(medicineList.get(i));
}else{
addList.add(medicineList.get(i));
}
}
intupdate=0;
intadd=0;
if(updateList!=null&&updateList.size()>0){
update=medicineService.updateMedicine(updateList);
}
if(addList!=null&&addList.size()>0){
add=medicineService.addMedicine(addList);
}
if(update>0||add>0){
returnnewResponseModel().attr(ResponseModel.KEY_DATA,"数据导入成功!");
}else{
returnnewResponseModel().attr(ResponseModel.KEY_ERROR,"数据导入失败!");
}
}catch(BiffExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}else{
returnnewResponseModel().attr(ResponseModel.KEY_ERROR,"没有需要导入的数据!");
}
returnnull;
}
导出
packagebeans.excel;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Calendar;
importjava.util.Date;
importjxl.Workbook;
importjxl.format.Colour;
importjxl.format.UnderlineStyle;
importjxl.write.Boolean;
importjxl.write.DateFormats;
importjxl.write.DateTime;
importjxl.write.Label;
importjxl.write.Number;
importjxl.write.WritableCellFormat;
importjxl.write.WritableFont;
importjxl.write.WritableSheet;
importjxl.write.WritableWorkbook;
importjxl.write.WriteException;
{
publicvoidcreateExcel(OutputStreamos)throwsWriteException,IOException{
//创建工作薄
WritableWorkbookworkbook=Workbook.createWorkbook(os);
//创建新的一页
WritableSheetsheet=workbook.createSheet("FirstSheet",0);
//构造表头
sheet.mergeCells(0,0,4,0);//添加合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
WritableFontbold=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//设置字体种类和黑体显示,字体为Arial,字号大小为10,采用黑体显示
=newWritableCellFormat(bold);//生成一个单元格样式控制对象
titleFormate.setAlignment(jxl.format.Alignment.CENTRE);//单元格中的内容水平方向居中
titleFormate.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//单元格的内容垂直方向居中
Labeltitle=newLabel(0,0,"JExcelApi支持数据类型详细说明",titleFormate);
sheet.setRowView(0,600,false);//设置第一行的高度
sheet.addCell(title);
//创建要显示的具体内容
WritableFontcolor=newWritableFont(WritableFont.ARIAL);//选择字体
color.setColour(Colour.GOLD);//设置字体颜色为金黄色
WritableCellFormatcolorFormat=newWritableCellFormat(color);
Labelformate=newLabel(0,1,"数据格式",colorFormat);
sheet.addCell(formate);
Labelfloats=newLabel(1,1,"浮点型");
sheet.addCell(floats);
Labelintegers=newLabel(2,1,"整型");
sheet.addCell(integers);
Labelbooleans=newLabel(3,1,"布尔型");
sheet.addCell(booleans);
Labeldates=newLabel(4,1,"日期格式");
sheet.addCell(dates);
Labelexample=newLabel(0,2,"数据示例",colorFormat);
sheet.addCell(example);
//浮点数据
//设置下划线
WritableFontunderline=newWritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.NO_BOLD,false,UnderlineStyle.SINGLE);
=newWritableCellFormat(underline);
greyBackground.setBackground(Colour.GRAY_25);//设置背景颜色为灰色
Numbernumber=newNumber(1,2,3.1415926535,greyBackground);
sheet.addCell(number);
//整形数据
WritableFontboldNumber=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//黑体
=newWritableCellFormat(boldNumber);
Numberints=newNumber(2,2,15042699,boldNumberFormate);
sheet.addCell(ints);
//布尔型数据
Booleanbools=newBoolean(3,2,true);
sheet.addCell(bools);
//日期型数据
//设置黑体和下划线
WritableFontboldDate=newWritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD,false,UnderlineStyle.SINGLE);
=newWritableCellFormat(boldDate,DateFormats.FORMAT1);
Calendarc=Calendar.getInstance();
Datedate=c.getTime();
DateTimedt=newDateTime(4,2,date,boldDateFormate);
sheet.addCell(dt);
//把创建的内容写入到输出流中,并关闭输出流
workbook.write();
workbook.close();
os.close();
}
}
❼ java导出数据到excel的几种方法的比较
Excel的两种导出入门方法(JAVA与JS)
最近在做一个小项目作为练手,其中使用到了导出到Excel表格,一开始做的是使用JAVA的POI导出的,但因为我的数据是爬虫爬出来的,数据暂时并不保存在数据库或后台,所以直接显示在HTML的table,需要下载时又要将数据传回后台然后生成Excel文件,最后再从服务器下载到本地,过程几度经过网络传输,感觉比较耗时与浪费性能,于是想着在HTML中的Table直接导到Excel中节约资源
JAVA导出EXCEL(.xls)
导出Excel用的插件是apache的poi.jar,maven地址如下
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version></dependency>
1. 简单应用
先来个简化无样式的Excel导出,由于我的数据存在JSON中,所以形参是JSONArray,朋友们根据自己的实际数据类型(Map,List,Set等)传入即可 ,代码如下
/**
* 创建excel并填入数据
* @author LiQuanhui
* @date 2017年11月24日 下午5:25:13
* @param head 数据头
* @param body 主体数据
* @return HSSFWorkbook
*/
public static HSSFWorkbook expExcel(JSONArray head, JSONArray body) { //创建一个excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook(); //创建一个sheet工作表
HSSFSheet sheet = workbook.createSheet("学生信息");
//创建第0行表头,再在这行里在创建单元格,并赋值
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null; for (int i = 0; i < head.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(head.getString(i));//设置值
}
//将主体数据填入Excel中
for (int i = 0, isize = body.size(); i < isize; i++) {
row = sheet.createRow(i + 1);
JSONArray stuInfo = body.getJSONArray(i); for (int j = 0, jsize = stuInfo.size(); j < jsize; j++) {
cell = row.createCell(j);
cell.setCellValue(stuInfo.getString(j));//设置值
}
} return workbook;
}
创建好Excel对象并填好值后(就是得到workbook),就是将这个对象以文件流的形式输出到本地上去,代码如下
/**
* 文件输出
* @author LiQuanhui
* @date 2017年11月24日 下午5:26:23
* @param workbook 填充好的workbook
* @param path 存放的位置
*/
public static void outFile(HSSFWorkbook workbook,String path) {
OutputStream os=null; try {
os = new FileOutputStream(new File(path));
workbook.write(os);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
至此Excel的导出其实已经做完了。
2. 添加样式后导出
但通常这并不能满足我们的需求,因为通常是需要设置Excel的一些样式的,如字体、居中等等,设置单元格样式主要用到这个类(HSSFCellStyle)
HSSFCellStyle cellStyle = workbook.createCellStyle();
现在说说HSSFCellStyle都能干些什么
HSSFCellStyle cellStyle = workbook.createCellStyle();//创建单元格样式对象1.设置字体
HSSFFont font = workbook.createFont(); //font.setFontHeight((short)12);//这个设置字体会很大
font.setFontHeightInPoints((short)12);//这才是我们平常在Excel设置字体的值
font.setFontName("黑体");//字体:宋体、华文行楷等等
cellStyle.setFont(font);//将该字体设置进去2.设置对齐方式
cellStyle.setAlignment(horizontalAlignment);//horizontalAlignment参考下面给出的参数
//以下是最常用的三种对齐分别是居中,居左,居右,其余的写代码的时候按提示工具查看即可
HorizontalAlignment.CENTER
HorizontalAlignment.LEFT
HorizontalAlignment.RIGHT3.设置边框
cellStyle.setBorderBottom(border); // 下边框
cellStyle.setBorderLeft(border);// 左边框
cellStyle.setBorderTop(border);// 上边框
cellStyle.setBorderRight(border);// 右边框
//border的常用参数如下
BorderStyle.NONE 无边框
BorderStyle.THIN 细边框
BorderStyle.MEDIUM 中等粗边框
BorderStyle.THICK 粗边框//其余的我也描述不清是什么形状,有兴趣的到时可以直接测试
在经过一系列的添加样式之后,最后就会给单元格设置样式
cell.setCellStyle(cellStyle);
3. 自动调整列宽
sheet.autoSizeColumn(i);//i为第几列,需要全文都单元格居中的话,需要遍历所有的列数
4. 完整的案例
public class ExcelUtils { /**
* 创建excel并填入数据
* @author LiQuanhui
* @date 2017年11月24日 下午5:25:13
* @param head 数据头
* @param body 主体数据
* @return HSSFWorkbook
*/
public static HSSFWorkbook expExcel(JSONArray head, JSONArray body) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("学生信息");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
HSSFCellStyle cellStyle = workbook.createCellStyle();
setBorderStyle(cellStyle, BorderStyle.THIN);
cellStyle.setFont(setFontStyle(workbook, "黑体", (short) 14));
cellStyle.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i < head.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(head.getString(i));
cell.setCellStyle(cellStyle);
}
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
setBorderStyle(cellStyle2, BorderStyle.THIN);
cellStyle2.setFont(setFontStyle(workbook, "宋体", (short) 12));
cellStyle2.setAlignment(HorizontalAlignment.CENTER); for (int i = 0, isize = body.size(); i < isize; i++) {
row = sheet.createRow(i + 1);
JSONArray stuInfo = body.getJSONArray(i); for (int j = 0, jsize = stuInfo.size(); j < jsize; j++) {
cell = row.createCell(j);
cell.setCellValue(stuInfo.getString(j));
cell.setCellStyle(cellStyle2);
}
} for (int i = 0, isize = head.size(); i < isize; i++) {
sheet.autoSizeColumn(i);
} return workbook;
} /**
* 文件输出
* @author LiQuanhui
* @date 2017年11月24日 下午5:26:23
* @param workbook 填充好的workbook
* @param path 存放的位置
*/
public static void outFile(HSSFWorkbook workbook,String path) {
OutputStream os=null; try {
os = new FileOutputStream(new File(path));
workbook.write(os);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 设置字体样式
* @author LiQuanhui
* @date 2017年11月24日 下午3:27:03
* @param workbook 工作簿
* @param name 字体类型
* @param height 字体大小
* @return HSSFFont
*/
private static HSSFFont setFontStyle(HSSFWorkbook workbook, String name, short height) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(height);
font.setFontName(name); return font;
} /**
* 设置单元格样式
* @author LiQuanhui
* @date 2017年11月24日 下午3:26:24
* @param workbook 工作簿
* @param border border样式
*/
private static void setBorderStyle(HSSFCellStyle cellStyle, BorderStyle border) {
cellStyle.setBorderBottom(border); // 下边框
cellStyle.setBorderLeft(border);// 左边框
cellStyle.setBorderTop(border);// 上边框
cellStyle.setBorderRight(border);// 右边框
}
}
POI的功能其实还是很强大的,这里只介绍了Excel的一丁点皮毛给入门的查看,如果想对Excel进行更多的设置可以查看下面的这篇文章,有着大量的使用说明。
空谷幽澜的POI使用详解
JS导出EXCEL(.xls)
java的Excel导出提供了强大的功能,但也对服务器造成了一定资源消耗,若能使用客户端的资源那真是太好了
1. 简单应用
JS的导出Excel非常简单,只需要引用Jquery和tableExport.js并设置一个属性即可
<script src="<%=basePath%>/static/js/tableExport.js" type="text/javascript"></script><script type="text/javascript">
function exportExcelWithJS(){ //获取要导出Excel的表格对象并设置tableExport方法,设置导出类型type为excel
$('#tableId').tableExport({ type:'excel'
});
}</script><button class="btn btn-primary" type="button" style="float: right;" onclick="exportExcelWithJS()">下载本表格</button>
JS的导出就完成了,是不是特别简单
2. 进阶应用
但上面仅仅是个简单的全表无样式的导出
这tableExport.js还有一些其他功能,忽略行,忽略列,设置样式等,属性如下
<script type="text/javascript">
function exportExcelWithJS(){ //获取要导出Excel的表格对象并设置tableExport方法,设置导出类型type为excel
$('#tableId').tableExport({ type:'excel',//导出为excel
fileName:'2017工资表',//文件名
worksheetName:'11月工资',//sheet表的名字
ignoreColumn:[0,1,2],//忽略的列,从0开始算
ignoreRow:[2,4,5],//忽略的行,从0开始算
excelstyles:['text-align']//使用样式,不用填值只写属性,值读取的是html中的
});
}</script>
如上既是JS的进阶导出,操作简单,容易上手
但有个弊端就是分页的情况下,只能导出分页出的数据,毕竟这就是导出HTML内TABLE有的东西,数据在数据库或后台的也就无能为力,所以这个适合的是无分页的TABLE导出
3. 额外说明
tableExport.js是gitHub上的hhurz大牛的一个开源项目,需要下载该JS的可以点击链接进入gitHub下载或在我的网络网盘下载密码:oafu
tableExport.js不仅仅是个导出Excel的JS,他还可以导出CSV、DOC、JSON、PDF、PNG、SQL、TSV、TXT、XLS (Excel 2000 HTML format)、XLSX (Excel 2007 Office Open XML format)、XML (Excel 2003 XML Spreadsheet format)、XML (Raw xml)多种格式,具体使用可以参考hhurz的使用介绍
本人在之前找了好几个导出Excel的都有各种各样的问题(乱码,无响应,无样式),这个是目前找到最好的一个了,能解决乱码问题,能有样式,非常强大
❽ java代码怎么导出excel文件
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
java导出Excel
java 代码 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.serv ...
java导出Excel例举方式
方法一:导出Excel数据的插件jexcelapi
程序实例如下:
public void exportClassroom(OutputStream os) throws PaikeException {
try {
WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件
WritableSheet wsheet = wbook.createSheet("教室信息表", 0); //工作表名称
//设置Excel字体
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,
WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
WritableCellFormat titleFormat = new WritableCellFormat(wfont);
String[] title = { "教室名", "容 量", "类 型", "其他说明" };
//设置Excel表头
for (int i = 0; i < title.length; i++) {
Label excelTitle = new Label(i, 0, title[i], titleFormat);
wsheet.addCell(excelTitle);
}
int c = 1; //用于循环时Excel的行号
ClassroomService cs = new ClassroomService();
List list = cs.findAllClassroom(); //这个是从数据库中取得要导出的数据
Iterator it = list.iterator();
while (it.hasNext()) {
ClassroomDTO crdto = (ClassroomDTO) it.next();
Label content1 = new Label(0, c, crdto.getRoomname());
Label content2 = new Label(1, c, crdto.getCapicity().toString());
Label content3 = new Label(2, c, crdto.getRoomTypeId()
.toString());
Label content4 = new Label(3, c, crdto.getRemark());
wsheet.addCell(content1);
wsheet.addCell(content2);
wsheet.addCell(content3);
wsheet.addCell(content4);
c++;
}
wbook.write(); //写入文件
wbook.close();
os.close();
} catch (Exception e) {
throw new PaikeException("导出文件出错");
}
}
方法二:直接用Java代码实现导出Excel报表
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.axon.fable.sams.view.action;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.axon.fable.empolderpackage.out.OutJavaScript;
import com.axon.fable.empolderpackage.page.Pager;
import com.axon.fable.empolderpackage.string.MyPublic;
import com.axon.fable.sams.common.BaseAction;
import com.axon.fable.sams.exception.AppBusinessException;
import com.axon.fable.sams.exception.AppSystemException;
/**
* MyEclipse Struts
* Creation date: 06-28-2007
*
* XDoclet definition:
* @struts.action path="/axon" name="axonForm" input="/samspage/zm/axon.jsp" parameter="method" scope="request" validate="true"
* @struts.action-forward name="success" path="/samspage/zm/content.jsp"
*/
public class StshipoperationAction extends BaseAction {
/*
* Generated Methods
*/
private static Session session=null;
private static Transaction ts=null;
private static Query queryC=null;
private static Query queryR=null;
private static Query query=null;
private static List list=null;
private static Integer startRow;
private static Integer ncurrentPage;
private static Integer cell;
private static String property;
private static String sql;
private static String type;
private static String condition ;//是否导出当前页
private static String currentPage;
private static String from ;
private static String pactdata;
private static String voyagename;
private static String voyageno;
private static String dwt ;
private static String hirefrom ;
private static String deliveryposion ;
private static String redeliveryposion ;
private static String sheepowner ;
private static String addr;
private static String addcomm;
private static String rent;
private static String fileName ;
private static OutputStream os;
@Override
public ActionForward findAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
return null;
}
@Override
public ActionForward findById(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
return null;
}
@Override
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
return null;
}
public static String strNull(Object nullStr,String newStr,Integer cell){
if(nullStr==null||nullStr.equals("")){return newStr;}else{cell+=1;return nullStr+"";}
}
public static String getStr(String str,Integer cell){
if(str==null||str.trim().equals("")){return "";}else{cell+=1;return ","+str;}
}
public static String getExcelTile(String title){
if(title==null)
return "";
if(title.equals("modela.stsid"))
return "编号";
if(title.equals("modelc.pactdata"))
return "合同日期";
if(title.equals("modela.voyagename"))
return "航名";
if(title.equals("modela.voyageno"))
return "航次";
if(title.equals("modelc.dwt"))
return "DWT";
if(title.equals("modelc.hirefrom"))
return "受载期";
if(title.equals("modela.deliveryposion"))
return "交船地点";
if(title.equals("modela.redeliveryposion"))
return "还船地点";
if(title.equals("modelc.sheepowner"))
return "联系人";
if(title.equals("modelc.addr"))
return "经纪人拥金";
if(title.equals("modelc.addcomm"))
return "ADD COMM";
if(title.equals("modelc.rent"))
return "租金";
return "";
}
public ActionForward exporVoyagesInfoToExcel(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
list=null;
startRow=0;
ncurrentPage=1;
cell=0;
type =request.getParameter("type");
condition =request.getParameter("condition");//是否导出当前页
currentPage =request.getParameter("currentPage");
from =request.getParameter("from");
pactdata = request.getParameter("modelc.pactdata");
voyagename = request.getParameter("modela.voyagename");
voyageno = request.getParameter("modela.voyageno");
dwt = request.getParameter("modelc.dwt");
hirefrom = request.getParameter("modelc.hirefrom");
deliveryposion = request.getParameter("modela.deliveryposion");
redeliveryposion = request.getParameter("modela.redeliveryposion");
sheepowner = request.getParameter("modelc.sheepowner");
addr = request.getParameter("modelc.addr");
addcomm = request.getParameter("modelc.addcomm");
rent = request.getParameter("modelc.rent");
if(type!=null&&type.trim().equals("1")){
type ="已还船舶--费用未结清";
}else{
type ="已还船舶--费用已结清";
}
property =getStr(pactdata,cell)+getStr(voyagename,cell)+getStr(voyageno,cell)+getStr(dwt,cell)+getStr(hirefrom,cell)
+getStr(deliveryposion,cell)+getStr(redeliveryposion,cell)+getStr(sheepowner,cell)+getStr(addr,cell)+getStr(addcomm,cell)
+getStr(rent,cell);
property = property.substring(1);
String split[] = property.split(",");
// System.out.println("-----------------------------property:"+property);
if(currentPage!=null&&!currentPage.trim().equals("")){
ncurrentPage =Integer.parseInt(currentPage);
}else{
OutJavaScript.outString(response, "Sorry! Failed to get information of pager.");
return null;
}
try {
session =getServiceLocator().getBaseHibernateDAO().getSession();
sql ="select count(*) "+from;
query =session.createQuery(sql);
list = query.list();
for (int i = 0; i < list.size(); i++) {
totalSize =(Integer)list.get(i);
if(totalSize!=0){
pager =new Pager(ncurrentPage,totalSize);
}
}
query =getServiceLocator().getBaseHibernateDAO().getSession().createQuery("select " +property+from);
if(condition!=null&&condition.trim().equals("1")){//分页数据
startRow = (ncurrentPage - 1)*pager.getPageSize();
query.setFirstResult(startRow);
query.setMaxResults(pager.getPageSize());
// System.out.println("---------------------------------------------------query:"+query);
}
list = query.list();
fileName = "shipInfo";
os = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition",
"attachment; filename=" +fileName + ".xls");
response.setContentType("application/msexcel");
jxl.write.WritableWorkbook wbook = Workbook.createWorkbook(os);
jxl.write.WritableSheet wsheet = wbook.createSheet("the first sheet", 0);
for (int i = 0; i < split.length; i++) {
jxl.write.Label wlabel0;
wlabel0 = new jxl.write.Label(i, 0, getExcelTile(split[i]));
wsheet.addCell(wlabel0);
}
jxl.write.Label wlabel1;
for(int i=0;i<list.size();i++) {
if(split.length==1){
Object strval = (Object) list.get(i);
String javaScript=""+MyPublic.toHtmlStr(strval==null?"":strval.toString().trim())+"";
wlabel1 = new jxl.write.Label(0, i+1,strval==null?"":strval.toString().trim() );
wsheet.addCell(wlabel1);
}else{
Object[] strval = (Object[]) list.get(i);
for(int j=0;j<strval.length;j++) {
String javaScript=""+MyPublic.toHtmlStr(strval[j]==null?"":strval[j].toString().trim())+"";
//System.out.println("===================script:"+javaScript);
wlabel1 = new jxl.write.Label(j, i+1,strval[j]==null?"":strval[j].toString().trim() );
wsheet.addCell(wlabel1);
}
}
}
wbook.write();
response.flushBuffer();
wbook.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
OutJavaScript.outString(response, "Sorry! Export Excel exception.");
e.printStackTrace();
} catch (HibernateException e1) {
// TODO Auto-generated catch block
OutJavaScript.outString(response, "Sorry! Database exception.");
e1.printStackTrace();
} catch (AppSystemException e1) {
// TODO Auto-generated catch block
OutJavaScript.outString(response, "Sorry! System exception.");
e1.printStackTrace();
} catch (AppBusinessException e1) {
// TODO Auto-generated catch block
OutJavaScript.outString(response, "Sorry! Database exception.");
e1.printStackTrace();
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
OutJavaScript.outString(response, "Sorry! Export Excel exception.");
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
OutJavaScript.outString(response, "Sorry! Export Excel exception.");
e.printStackTrace();
}
return null;
}
@Override
public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
return null;
}
}
还有其他很多种 字数限制 无法一一举例方式