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();
// }
}
}
}