❶ 在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;
}
}
還有其他很多種 字數限制 無法一一舉例方式