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架包