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 压缩POI生成的EXCEL
看出错信来息,需要用XSSF处理源,是你读取的文件格式不对吧,获取的file是XML文件吗?可以加一句System.out.pringtln(file.getName())看看,poi是处理excel的。
⑶ eclipse如何导出工程zip压缩包
1、在要导出的项目上点击鼠标右键,选择Export。
⑷ java怎么导出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; i<users.length;i++) { // 相当于excel表格中的总行数
PropertyDescriptor[] descriptors=(users[i]);
rows[i]=s.createRow(i);
for (int j=0; descriptors!=null&&j<descriptors.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 如何将多个excl生成zip文件下载
/**
* 压缩文件zip-Apache中ant所带包
* @功能信息 :
* @参数信息 :
* @返回值信息 :
* @异常信息 :
* */
public void getZip(List list,String path,String fileName) throws Exception{
byte[] buffer = new byte[1024];
String strZipName = fileName + ".zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path
+ strZipName));
for (int j = 0; j < list.size(); j++) {
String name = list.get(j).toString();
FileInputStream fis = new FileInputStream(path + name);
out.putNextEntry(new ZipEntry(name));
int len;
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
System.out.println("生成Demo.zip成功");
}
⑹ java :怎么实现分批次导出excel的条数限制,每次导出的excel压缩成zip,并且导出时给用户添加友好提示
你这问题太大了
HSSFWorkbook 是导出的工具,可是实现导出excel控制条数
//开始打印
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("sheet1");
HSSFRow row = sheet.createRow(0);
//设置第一行标题
HSSFCell cell;
JobColumn jobColumn = null;
int colsAddSize = NewmasterstudentAction.COLS4EXPORT_CODE.length;
for(int i=0 ; i<colsAddSize ; i++){
cell = row.createCell((short)i);
cell.setCellValue(NewmasterstudentAction.COLS4EXPORT_CODE[i]+"("+NewmasterstudentAction.COLS4EXPORT_NAME[i]+")");
}
for(int i=0;i<jobList.size();i++){
UserJobColumn userJob = jobList.get(i);
jobColumn = userJob.getJobColumn();
cell = row.createCell((short)(i+colsAddSize));
cell.setCellValue(jobColumn.getColumnCode()+"("+jobColumn.getColumnName()+")"); //字段代码
}
//打印记录
Set<Entry<String,List<JobRecord>>> entrySet = des.entrySet();
Iterator<Entry<String, List<JobRecord>>> it = entrySet.iterator();
int index = 1;
while(it.hasNext()){
Entry<String, List<JobRecord>> en = it.next();
row = sheet.createRow(index++);
String xh = en.getKey();
//打印学生信息
cell = row.createCell((short)0);
cell.setCellValue(xh);
NewMasterStudent stu = studentMap.get(xh);
if(stu != null){
cell = row.createCell((short)1);
cell.setCellValue(stu.getYbd() ? "是" : "否");
cell = row.createCell((short)2);
cell.setCellValue(stu.getRemark() == null ? "" : stu.getRemark());
}
//打印记录
List<JobRecord> records = en.getValue();
for(int i=0 ; i <jobList.size() ; i++){
cell = row.createCell((short)(i+colsAddSize));
UserJobColumn g = jobList.get(i);
JobRecord record = null;
if(i < records.size()){
record = records.get(i);
if(!g.getJobColumn().getId().equals(record.getJobColumn().getId())){
record = new JobRecord();
record.setJobColumn(g.getJobColumn());
records.add(i, record);
}
}else{
record = new JobRecord();
record.setJobColumn(g.getJobColumn());
records.add(i, record);
}
if(Constant.NS_JOBCOLUMN_TYPE_INPUT.equals(record.getJobColumn().getColumnType())){
cell.setCellValue(record.getEditLr());
}else if(Constant.NS_JOBCOLUMN_TYPE_SELECT.equals(record.getJobColumn().getColumnType())){
cell.setCellValue(record.isEditState() ? "是":"否");
}else if(Constant.NS_JOBCOLUMN_TYPE_OPTION.equals(record.getJobColumn().getColumnType())){
SyGeneralCode select = record.getSelectedValue();
if(select != null){
cell.setCellValue(select.getCode()+" | "+select.getCnName());
}
}
}
}
ZipEntry 可以实现导出zip文件
if (files[i].exists() && !files[i].isDirectory()) {
String zjhmImg = files[i].getName();
if (zjhmMap.get(zjhmImg) != null) {
num++;
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i].getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
out.setEncoding("GBK");
origin.close();
⑺ java代码实现 导出zip包,无法打开zip压缩包
package com.lch.test;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZIP {
public static void main(String[] argv) throws Exception {
ZipFile zf = new ZipFile("E:\\wk\\LBSLEMIS201106141057\\LBSLEMIS\\test\\com\\lch\\test\\filename.zip");
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String zipEntryName = ((ZipEntry) entries.nextElement()).getName();
System.out.println(zipEntryName);
}
}
}
用javad 的ZipFile类的ZipEntry方法试一下 找到ZIP里面的ZipEntry方法 读取Zip里面压缩文件的内容
有可能会引用外包
你好,我不知道你说的dzp是什么格式文件,但如果是zip的压缩文件,可以看下我的这段代码
ZipFile file = new ZipFile("d:\\1.zip");
ZipEntry entry = file.getEntry("1.xml"); //假如压缩包里的文件名是1.xml
InputStream in=file.getInputStream(entry);
最后就是按照java中一贯的流的处理方式即可
可以不解压,zip包里的一个对象就是一个ZipEntry
找到你想要的那个ZipEntry,用文流写出来就可以了。追问通过ZipEntry,然后用流就可以读出里面的内容了吗?谢谢指点!
回答/**
* 解压
* @param root 输出目标
* @param zipfile zip文件
*/
protected void unzip(File root, File zipfile, String file) throws Exception {
// 解压文件不存在时返回
if (!zipfile.exists()) {
return;
}
// 释放目录不存时创建
if (!root.exists()) {
root.mkdirs();
}
// 释放目录不为目录时返回
if (!root.isDirectory()) {
return;
}
FileInputStream fin = new FileInputStream(zipfile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry entry = null;
while ((entry = zin.getNextEntry()) != null) {
// if (!entry.getName().endsWith(file)) {
// continue;
// }
File tmp = new File(root, entry.getName());
if (entry.isDirectory()) {
tmp.mkdirs();
} else {
byte[] buff = new byte[4096];
int len = 0;
tmp.getParentFile().mkdirs();
FileOutputStream fout = new FileOutputStream(tmp);
while ((len = zin.read(buff)) != -1) {
fout.write(buff, 0, len);
}
zin.closeEntry();
fout.close();
}
}
}
这里完整的解压代码。
// if (!entry.getName().endsWith(file)) {
// continue;
// }
这段打开就是只解出一个你指定的文件。
下面是测试用的。
public static void main(String[] args) throws Exception {
new CommonFiles().unzip(new File("D:\\"), new File("D:\\test.zip"),"file.txt");
}
这个例子会在D盘生成型个test文件夹,file.txt就会在里面,(里面也可能会有多个文件夹,这个取决于压缩包里文件的度)
⑻ javaweb 导出excel需要哪些jar包
java导出Excel需要用到poi的jar包,
// 第一步,创建一个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 打包后导出看不到文件
是不是在来 vista 或 Windows 7 下运行源,如果是这样用管理员身份运行试试。
FileOutputStream fileOut = new FileOutputStream(outFileName);
wb.write(fileOut);
fileOut.close(); //是不是没写这句?
⑽ java导出excel
wb = Workbook.getWorkbook(file);//按路径获取抄excel表
Sheet sheet = wb.getSheet(0);//第一个工作簿
sheet.getCell(x,y).getContents())//获取x列y行的数据;
需要一个jxl架包