「java导出excel实例」java Excel导出

博主:adminadmin 2022-12-31 12:57:06 926

今天给各位分享java导出excel实例的知识,其中也会对java Excel导出进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

怎么用java实现导出excel

/**

 * @author liuwu

 * Excel的导入与导出

 */

@SuppressWarnings({ "unchecked" })

public class ExcelOperate {

/**

 * @author liuwu

 * 这是一个通用的方法,利用了JAVA的反射机制,

 * 可以将放置在JAVA集合中并且符合一定条件的数据以EXCEL的形式输出到指定IO设备上

 * @param title 表格标题名

 * @param headers 表格属性列名数组

 * @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。

 *  此方法支持的 javabean属性【数据类型有java基本数据类型及String,Date,byte[](图片转成字节码)】

 * @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中

 * @param pattern  如果有时间数据,设定输出格式。默认为"yyy-MM-dd"

 * @throws IOException 

 */

public static void exportExcel(String title, String[] headers,Collection? dataset, OutputStream out, String pattern) throws IOException {

// 声明一个工作薄

HSSFWorkbook workbook = new HSSFWorkbook();

// 生成一个表格

HSSFSheet sheet = workbook.createSheet(title);

// 设置表格默认列宽度为15个字节

sheet.setDefaultColumnWidth((short) 20);

// 生成一个样式

HSSFCellStyle style = workbook.createCellStyle();

// 设置这些样式

style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style.setBorderRight(HSSFCellStyle.BORDER_THIN);

style.setBorderTop(HSSFCellStyle.BORDER_THIN);

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

// 生成一个字体

HSSFFont font = workbook.createFont();

font.setColor(HSSFColor.VIOLET.index);

font.setFontHeightInPoints((short) 12);

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// 把字体应用到当前的样式

style.setFont(font);

// 生成并设置另一个样式

HSSFCellStyle style2 = workbook.createCellStyle();

style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);

style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style2.setBorderRight(HSSFCellStyle.BORDER_THIN);

style2.setBorderTop(HSSFCellStyle.BORDER_THIN);

style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

// 生成另一个字体

HSSFFont font2 = workbook.createFont();

font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

// 把字体应用到当前的样式

style2.setFont(font2);

// 产生表格标题行

HSSFRow row = sheet.createRow(0);

for (short i = 0; i  headers.length; i++) {

HSSFCell cell = row.createCell(i);

cell.setCellStyle(style);

HSSFRichTextString text = new HSSFRichTextString(headers[i]);

cell.setCellValue(text);

}

// 遍历集合数据,产生数据行

Iterator? it = dataset.iterator();

int index = 0;

while (it.hasNext()) {

index++;

row = sheet.createRow(index);

Object t =  it.next();

// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值

Field[] fields = t.getClass().getDeclaredFields();

for (short i = 0; i  fields.length; i++) {

HSSFCell cell = row.createCell(i);

cell.setCellStyle(style2);

Field field = fields[i];

String fieldName = field.getName();

String getMethodName = "get"

+ fieldName.substring(0, 1).toUpperCase()

+ fieldName.substring(1);//注意 实体get Set不要自己改名字不然反射会有问题

try {

Class tCls = t.getClass();

Method getMethod = tCls.getMethod(getMethodName,new Class[] {});

Object value = getMethod.invoke(t, new Object[] {});

HSSFRichTextString richString = new HSSFRichTextString(value.toString());

HSSFFont font3 = workbook.createFont();

font3.setColor(HSSFColor.BLUE.index);

richString.applyFont(font3);

cell.setCellValue(richString);

} catch (SecurityException e) {

e.printStackTrace();

e=null;

} catch (NoSuchMethodException e) {

e.printStackTrace();

e=null;

} catch (IllegalArgumentException e) {

e.printStackTrace();

e=null;

} catch (IllegalAccessException e) {

e.printStackTrace();

e=null;

} catch (InvocationTargetException e) {

e.printStackTrace();

e=null;

} finally {

// 清理资源

}

}

}

try {

workbook.write(out);

} catch (IOException e) {

e.printStackTrace();

e=null;

}

}

}

java怎么实现导出excel

偶将最近写了两个导出excel的方法,第一个是面向过程的思路,就是在指定的单元格写入指定的值,如下:

/**

*负责数据导入到EXCEL

*

* @param realPath

* EXCEL表格存放的绝对路径

* @param sheetname

*

* @param xLocation

* EXCEL表格的行索引,从1开始

* @param yLocation

* EXCEL表格的列索引,从1开始

* @param value

* 需要导入的数据

*

*/

public void modifyExcel(String realPath,String sheetname,int xLocaion,int yLocation,String value){

POIFSFileSystem fs=null;

HSSFWorkbook wb=null;

try {

File file=new File(realPath);

if(file.exists()){

fs = new POIFSFileSystem(new FileInputStream(realPath));

wb=new HSSFWorkbook(fs);

HSSFSheet s=wb.getSheetAt(0);

//函数处理时横纵坐标从索引0开始

HSSFRow row=s.getRow(xLocaion-1);

HSSFCell cell=null;

if(row!=null){

cell=row.getCell(yLocation-1);

if(cell==null){

cell=row.createCell(yLocation-1);

}

}else{

row=s.createRow(xLocaion-1);

cell=row.createCell(yLocation-1);

}

cell.setCellValue(value);

}else{

wb=new HSSFWorkbook();

HSSFSheet s=wb.createSheet();

wb.setSheetName(0, sheetname);

HSSFRow row=s.createRow(xLocaion-1);

HSSFCell cell=row.createCell(yLocation-1);

cell.setCellValue(value);

}

FileOutputStream fos=new FileOutputStream(realPath);

wb.write(fos);

fos.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

第二种就是运用了对象,以对象为单位写入数据,即一个对象的所有属性在一行列出,有多少个对象就有多少行,此方法比较适用于个人信息导出之类的应用,至于导出属性的顺序问题在导出对象的实体类内部改动下即可:

/**

*负责数据导入到EXCEL

*

* @param realPath

* EXCEL表格存放的绝对路径

* @param sheetname

*

* @param users

* 需要导出到excel表的对象数组

*/

public void outputExcel(String realPath,String sheetname,UserModel[] users){

FileOutputStream fos;

try {

File file=new File(realPath);

fos = new FileOutputStream(file, true);

HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet s=wb.createSheet();

wb.setSheetName(0, sheetname);

HSSFRow[] rows=new HSSFRow[users.length];

HSSFCell[][] cells=new HSSFCell[20][20];

for (int i=0; iusers.length;i++) { // 相当于excel表格中的总行数

PropertyDescriptor[] descriptors=getAvailablePropertyDescriptors(users[i]);

rows[i]=s.createRow(i);

for (int j=0; descriptors!=nulljdescriptors.length;j++) {

java.lang.reflect.Method readMethod = descriptors[j]

.getReadMethod();

cells[i][j]=rows[i].createCell(j);

Object value=readMethod.invoke(users[i], null);

cells[i][j].setCellValue(value.toString());

}

}

wb.write(fos);

fos.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

}

java怎样输出excel文件

//java生成简单的Excel文件

package beans.excel;

import java.io.IOException;

import java.io.OutputStream;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

 

public class SimpleExcelWrite {

    public void createExcel(OutputStream os) throws WriteException,IOException{

        //创建工作薄

        WritableWorkbook workbook = Workbook.createWorkbook(os);

        //创建新的一页

        WritableSheet sheet = workbook.createSheet("First Sheet",0);

        //创建要显示的内容,创建一个单元格,第一个参数为列坐标,第二个参数为行坐标,第三个参数为内容

        Label xuexiao = new Label(0,0,"学校");

        sheet.addCell(xuexiao);

        Label zhuanye = new Label(1,0,"专业");

        sheet.addCell(zhuanye);

        Label jingzhengli = new Label(2,0,"专业竞争力");

        sheet.addCell(jingzhengli);

        

        Label qinghua = new Label(0,1,"清华大学");

        sheet.addCell(qinghua);

        Label jisuanji = new Label(1,1,"计算机专业");

        sheet.addCell(jisuanji);

        Label gao = new Label(2,1,"高");

        sheet.addCell(gao);

        

        Label beida = new Label(0,2,"北京大学");

        sheet.addCell(beida);

        Label falv = new Label(1,2,"法律专业");

        sheet.addCell(falv);

        Label zhong = new Label(2,2,"中");

        sheet.addCell(zhong);

        

        Label ligong = new Label(0,3,"北京理工大学");

        sheet.addCell(ligong);

        Label hangkong = new Label(1,3,"航空专业");

        sheet.addCell(hangkong);

        Label di = new Label(2,3,"低");

        sheet.addCell(di);

        

        //把创建的内容写入到输出流中,并关闭输出流

        workbook.write();

        workbook.close();

        os.close();

    }

    

}

java怎么导出excel表格

通过这个例子,演示以下如何用java生成excel文件:

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

import java.io.FileOutputStream;

import java.io.IOException;

publicclass CreateCells

{

publicstaticvoid main(String[] args)

throws IOException

{

HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象

HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet对象

// Create a row and put some cells in it. Rows are 0 based.

HSSFRow row = sheet.createRow((short)0);//建立新行

// Create a cell and put a value in it.

HSSFCell cell = row.createCell((short)0);//建立新cell

cell.setCellValue(1);//设置cell的整数类型的值

// Or do it on one line.

row.createCell((short)1).setCellValue(1.2);//设置cell浮点类型的值

row.createCell((short)2).setCellValue("test");//设置cell字符类型的值

row.createCell((short)3).setCellValue(true);//设置cell布尔类型的值

HSSFCellStyle cellStyle = wb.createCellStyle();//建立新的cell样式

cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"));//设置cell样式为定制的日期格式

HSSFCell dCell =row.createCell((short)4);

dCell.setCellValue(new Date());//设置cell为日期类型的值

dCell.setCellStyle(cellStyle); //设置该cell日期的显示格式

HSSFCell csCell =row.createCell((short)5);

csCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断

csCell.setCellValue("中文测试_Chinese Words Test");//设置中西文结合字符串

row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);//建立错误cell

// Write the output to a file

FileOutputStream fileOut = new FileOutputStream("workbook.xls");

wb.write(fileOut);

fileOut.close();

}

}

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