本文目录一览:

使用java将数据库中的数据导出到excel中

用jxl来实现

import jxl.Cell;

import jxl.Sheet;

import jxl.Workbook;public String importEnter(HttpServletRequest request) {

Connection conn = null;

PreparedStatement ps = null;

OpenDbBean db = new OpenDbBean();

String message = "";

try {

ServletInputStream is = request.getInputStream();

byte[] junk = new byte[1024];

int bytesRead = 0;

//去掉浏览器发送的垃圾信息

bytesRead = is.readLine(junk, 0, junk.length);

bytesRead = is.readLine(junk, 0, junk.length);

bytesRead = is.readLine(junk, 0, junk.length);

bytesRead = is.readLine(junk, 0, junk.length);

Workbook workbook = Workbook.getWorkbook(is);

//取得第一个工作录

Sheet sheet = workbook.getSheet(0);

//从第二行开始取数据并处理

Enter enter = new Enter();

//连接数据库

conn = db.getConnection();

String sql =

"insert into haocai_enter(enter_id,enter_time,amount,jsr,type_id,xh)"

+ " values(s_enter_id.nextval,to_date(?,'dd/mm/yyyy'),?,?,?,?)";

ps = conn.prepareStatement(sql);

int okCount = 0;

ArrayList errorRows = new ArrayList();

for (int i = 1; i sheet.getRows(); i++) {

DB mydb = new DB();

Cell[] c = sheet.getRow(i);

String type_id = enter.getTypeIdByPm(c[PM].getContents());

if (type_id != null) {

//设置入库数据

ps.setString(1, c[ENTER_TIME].getContents());

ps.setString(2, c[AMOUNT].getContents());

ps.setString(3, c[JSR].getContents());

ps.setString(4, type_id);

ps.setString(5, c[XH].getContents());

ps.addBatch();

okCount++;

} else {

message += "br第" + i + "行 " + c[PM].getContents() + " 导入失败";

}

}

//执行该批过程

if (okCount 0) {

ps.executeBatch();

}

message += "br成功导入" + okCount + " 行";

workbook.close();

} catch (Exception e) {

System.out.println(e.getMessage());

message += "br" + e.getMessage();

} finally {

try {

db.CleanConnection(conn, ps, null);

} catch (SQLException e1) {

e1.printStackTrace();

}

}

return message;

}

用jxl.jar或者poi都可以,poi可以到apache网站上去下。

利用Java 创建和读取Excel文档

为了保证示例程序的运行,必须安装Java 2 sdk1.4.0 和Jakarta POI,Jakarta POI的Web站点是:

示例1将演示如何利用Jakarta POI API 创建Excel 文档。

示例1程序如下:

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFCell;

import java.io.FileOutputStream;

public class CreateXL {

/** Excel 文件要存放的位置,假定在D盘JTest目录下*/

public static String outputFile="D:/JTest/ gongye.xls";

public static void main(String argv[])

{

try

{

// 创建新的Excel 工作簿

HSSFWorkbook workbook = new HSSFWorkbook();

// 在Excel工作簿中建一工作表,其名为缺省值

// 如要新建一名为"效益指标"的工作表,其语句为:

// HSSFSheet sheet = workbook.createSheet("效益指标");

HSSFSheet sheet = workbook.createSheet();

// 在索引0的位置创建行(最顶端的行)

HSSFRow row = sheet.createRow((short)0);

//在索引0的位置创建单元格(左上端)

HSSFCell cell = row.createCell((short) 0);

// 定义单元格为字符串类型

cell.setCellType(HSSFCell.CELL_TYPE_STRING);

// 在单元格中输入一些内容

cell.setCellValue("增加值");

// 新建一输出文件流

FileOutputStream fOut = new FileOutputStream(outputFile);

// 把相应的Excel 工作簿存盘

workbook.write(fOut);

fOut.flush();

// 操作结束,关闭文件

fOut.close();

System.out.println("文件生成...");

}catch(Exception e) {

System.out.println("已运行 xlCreate() : " + e );

}

}

}

读取Excel文档中的数据

示例2将演示如何读取Excel文档中的数据。假定在D盘JTest目录下有一个文件名为gongye.xls的Excel文件。

示例2程序如下:

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFCell;

import java.io.FileInputStream;

public class ReadXL {

/** Excel文件的存放位置。注意是正斜线*/

public static String fileToBeRead="D:/JTest/ gongye.xls";

public static void main(String argv[]){

try{

// 创建对Excel工作簿文件的引用

HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));

// 创建对工作表的引用。

// 本例是按名引用(让我们假定那张表有着缺省名"Sheet1")

HSSFSheet sheet = workbook.getSheet("Sheet1");

// 也可用getSheetAt(int index)按索引引用,

// 在Excel文档中,第一张工作表的缺省索引是0,

// 其语句为:HSSFSheet sheet = workbook.getSheetAt(0);

// 读取左上端单元

HSSFRow row = sheet.getRow(0);

HSSFCell cell = row.getCell((short)0);

// 输出单元内容,cell.getStringCellValue()就是取所在单元的值

System.out.println("左上端单元是: " + cell.getStringCellValue());

}catch(Exception e) {

System.out.println("已运行xlRead() : " + e );

}

}

}

设置单元格格式

在这里,我们将只介绍一些和格式设置有关的语句,我们假定workbook就是对一个工作簿的引用。在Java

中,第一步要做的就是创建和设置字体和单元格的格式,然后再应用这些格式:

1、创建字体,设置其为红色、粗体:

HSSFFont font = workbook.createFont();

font.setColor(HSSFFont.COLOR_RED);

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

2、创建格式

HSSFCellStyle cellStyle= workbook.createCellStyle();

cellStyle.setFont(font);

3、应用格式

HSSFCell cell = row.createCell((short) 0);

cell.setCellStyle(cellStyle);

cell.setCellType(HSSFCell.CELL_TYPE_STRING);

cell.setCellValue("标题 ");

总之,如本篇文章所演示的一样,Java程序员不必担心Excel工作表中的数据了,利用Jakarta POI API,

我们就可以轻易的在程序中存取Excel文档。

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表格

可以使用POI开源的api:

1.首先下载poi-3.6-20091214.jar,下载地址如下:

2.Student.java

import java.util.Date;

public class Student

{

private int id;

private String name;

private int age;

private Date birth;

public Student()

{

}

public Student(int id, String name, int age, Date birth)

{

this.id = id;

this.name = name;

this.age = age;

this.birth = birth;

}

public int getId()

{

return id;

}

public void setId(int id)

{

this.id = id;

}

public String getName()

{

return name;

}

public void setName(String name)

{

this.name = name;

}

public int getAge()

{

return age;

}

public void setAge(int age)

{

this.age = age;

}

public Date getBirth()

{

return birth;

}

public void setBirth(Date birth)

{

this.birth = birth;

}

}

3.CreateSimpleExcelToDisk.java

import java.io.FileOutputStream;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateSimpleExcelToDisk

{

/**

* @功能:手工构建一个简单格式的Excel

*/

private static ListStudent getStudent() throws Exception

{

List list = new ArrayList();

SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "张三", 16, df.parse("1997-03-12"));

Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));

Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));

list.add(user1);

list.add(user2);

list.add(user3);

return list;

}

public static void main(String[] args) throws Exception

{

// 第一步,创建一个webbook,对应一个Excel文件

HSSFWorkbook wb = new HSSFWorkbook();

// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet

HSSFSheet sheet = wb.createSheet("学生表一");

// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short

HSSFRow row = sheet.createRow((int) 0);

// 第四步,创建单元格,并设置值表头 设置表头居中

HSSFCellStyle style = wb.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

HSSFCell cell = row.createCell((short) 0);

cell.setCellValue("学号");

cell.setCellStyle(style);

cell = row.createCell((short) 1);

cell.setCellValue("姓名");

cell.setCellStyle(style);

cell = row.createCell((short) 2);

cell.setCellValue("年龄");

cell.setCellStyle(style);

cell = row.createCell((short) 3);

cell.setCellValue("生日");

cell.setCellStyle(style);

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,

List list = CreateSimpleExcelToDisk.getStudent();

for (int i = 0; i list.size(); i++)

{

row = sheet.createRow((int) i + 1);

Student stu = (Student) list.get(i);

// 第四步,创建单元格,并设置值

row.createCell((short) 0).setCellValue((double) stu.getId());

row.createCell((short) 1).setCellValue(stu.getName());

row.createCell((short) 2).setCellValue((double) stu.getAge());

cell = row.createCell((short) 3);

cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu

.getBirth()));

}

// 第六步,将文件存到指定位置

try

{

FileOutputStream fout = new FileOutputStream("E:/students.xls");

wb.write(fout);

fout.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

java导出数据到excel的几种方法的比较

Excel的两种导出入门方法(JAVA与JS)

最近在做一个小项目作为练手,其中使用到了导出到Excel表格,一开始做的是使用JAVA的POI导出的,但因为我的数据是爬虫爬出来的,数据暂时并不保存在数据库或后台,所以直接显示在HTML的table,需要下载时又要将数据传回后台然后生成Excel文件,最后再从服务器下载到本地,过程几度经过网络传输,感觉比较耗时与浪费性能,于是想着在HTML中的Table直接导到Excel中节约资源

JAVA导出EXCEL(.xls)

导出Excel用的插件是apache的poi.jar,maven地址如下

dependency

groupIdorg.apache.poi/groupId

artifactIdpoi/artifactId

version3.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"/scriptscript type="text/javascript"

function exportExcelWithJS(){    //获取要导出Excel的表格对象并设置tableExport方法,设置导出类型type为excel

$('#tableId').tableExport({      type:'excel'

});

}/scriptbutton 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的功能?

import java.io.FileOutputStream;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateSimpleExcelToDisk

{

/**

* @功能:手工构建一个简单格式的Excel

*/

private static ListStudent getStudent() throws Exception

{

List list = new ArrayList();

SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "张三", 16, df.parse("1997-03-12"));

Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));

Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));

list.add(user1);

list.add(user2);

list.add(user3);

return list;

}

public static void main(String[] args) throws Exception

{

// 第一步,创建一个webbook,对应一个Excel文件

HSSFWorkbook wb = new HSSFWorkbook();

// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet

HSSFSheet sheet = wb.createSheet("学生表一");

// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short

HSSFRow row = sheet.createRow((int) 0);

// 第四步,创建单元格,并设置值表头 设置表头居中

HSSFCellStyle style = wb.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

HSSFCell cell = row.createCell((short) 0);

cell.setCellValue("学号");

cell.setCellStyle(style);

cell = row.createCell((short) 1);

cell.setCellValue("姓名");

cell.setCellStyle(style);

cell = row.createCell((short) 2);

cell.setCellValue("年龄");

cell.setCellStyle(style);

cell = row.createCell((short) 3);

cell.setCellValue("生日");

cell.setCellStyle(style);

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,

List list = CreateSimpleExcelToDisk.getStudent();

for (int i = 0; i list.size(); i++)

{

row = sheet.createRow((int) i + 1);

Student stu = (Student) list.get(i);

// 第四步,创建单元格,并设置值

row.createCell((short) 0).setCellValue((double) stu.getId());

row.createCell((short) 1).setCellValue(stu.getName());

row.createCell((short) 2).setCellValue((double) stu.getAge());

cell = row.createCell((short) 3);

cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu

.getBirth()));

}

// 第六步,将文件存到指定位置

try

{

FileOutputStream fout = new FileOutputStream("E:/students.xls");

wb.write(fout);

fout.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

在Java编程中怎么将从数据库查询出来的数据导成Excel文件?

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]);

}

}

}