toexceljava的简单介绍

博主:adminadmin 2023-03-19 18:36:07 366

本篇文章给大家谈谈toexceljava,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

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!=nulltype.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!=nullcondition.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;ilist.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;jstrval.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;

}

}

还有其他很多种 字数限制 无法一一举例方式

如何用java把数据写入到excel

需要导入jxl.jar

搭建环境

将下载后的文件解包,得到jxl.jar,放入classpath,安装就完成了。

创建文件

拟生成一个名为“测试数据.xls”的Excel文件,其中第一个工作表被命名为“第一页”,大致效果如下:

代码(CreateXLS.java):

//生成Excel的类

import java.io.*;

import jxl.*;

import jxl.write.*;

public class CreateXLS

{

public static void main(String args[])

{

try

{

//打开文件

WritableWorkbook book=

Workbook.createWorkbook(new File(“测试.xls”));

//生成名为“第一页”的工作表,参数0表示这是第一页

WritableSheet sheet=book.createSheet(“第一页”,0);

//在Label对象的构造子中指名单元格位置是第一列第一行(0,0)

//以及单元格内容为test

Label label=new Label(0,0,”test”);

//将定义好的单元格添加到工作表中

sheet.addCell(label);

/*生成一个保存数字的单元格

必须使用Number的完整包路径,否则有语法歧义

单元格位置是第二列,第一行,值为789.123*/

jxl.write.Number number = new jxl.write.Number(1,0,789.123);

sheet.addCell(number);

//写入数据并关闭文件

book.write();

book.close();

}catch(Exception e)

{

System.out.println(e);

}

}

}

编译执行后,会在当前位置产生一个Excel文件。

如何用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; ititle.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]);

}

}

}

toexceljava的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、toexceljava的信息别忘了在本站进行查找喔。