package com.testoutexcel;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class TestInExcel {
public static void main(String[] args) {
upload();
}
public static void upload() {
InputStream is = null;
jxl.Workbook book = null;
OutputStream os = null;
jxl.write.WritableWorkbook newBook = null;
jxl.write.WritableSheet newSheet = null;
try {
//创建工作薄
is = new FileInputStream("f://t.xls");
book = jxl.Workbook.getWorkbook(is);
//is.read();
//获取所有的工作表
jxl.Sheet[] sheets = book.getSheets();
//int sheetCount = sheets.length;
System.out.println("获取所有工作表成功");
//创建写入准备工作的book
os = new FileOutputStream("f://test2.xls");
newBook = jxl.Workbook.createWorkbook(os);
//遍历循环每个工作表
for(int i = 0;i < sheets.length; i++) {
jxl.Sheet sheet = (jxl.Sheet)book.getSheet(i);
System.out.println("获取每个工作表成功");
//获取每个表的名称
String sheetName = sheet.getName();
//创建写入准备工作的sheet
newSheet = newBook.createSheet(sheetName, i);
//获取表中的总列数
int columnCount = sheet.getColumns();
//获取表中的总行数
int rowCount = sheet.getRows();
//循环遍历每个单元格
for(int c = 0;c < columnCount;c++) {
for(int r = 0;r < rowCount;r++) {
//取出每个单元格
jxl.Cell cell = sheet.getCell(c, r);
System.out.println("取出每个单元格成功");
//获取每个单元格的超简单信息
String cellCont = cell.getContents();
jxl.CellType cellType = cell.getType();
System.out.println("--------------------");
//打印出每个单元格的超简单信息
System.out.println(cellCont + " and " + cellType);
//写入到一个新的文件中
try {
jxl.write.Label lable = new jxl.write.Label(c,r,cellCont);
newSheet.addCell(lable);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
}
newBook.write();
try {
newBook.close();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭读取相关
if(book != null)
book.close();
if(is != null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
//关闭写入相关
// if(os != null)
// try {
// os.close();
// } catch (IOException e1) {
// e1.printStackTrace();
// }
// if(newBook != null)
// try {
// newBook.close();
// } catch (WriteException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
}