jxl操作

jxl只能读2003 xls格式的,poi可以读2007,不是po

private static List<List<Object>> read2007Excel(File file) throws IOException {
List<List<Object>> list = new LinkedList<List<Object>>();
// 构造 XSSFWorkbook 对象,strPath 传入文件路径
XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
// 读取第一章表格内容
XSSFSheet sheet = xwb.getSheetAt(0);
Object value = null;
XSSFRow row = null;
XSSFCell cell = null;
for (int i = sheet.getFirstRowNum(); i <= sheet
.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
List<Object> linked = new LinkedList<Object>();
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
continue;
}
DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
System.out.println(i+"行"+j+" 列 is String type");
value = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
System.out.println(i+"行"+j+" 列 is Number type ; DateFormt:"+cell.getCellStyle().getDataFormatString());
if("@".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
} else if("General".equals(cell.getCellStyle().getDataFormatString())){
value = nf.format(cell.getNumericCellValue());
}else{
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
System.out.println(i+"行"+j+" 列 is Boolean type");
value = cell.getBooleanCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
System.out.println(i+"行"+j+" 列 is Blank type");
value = "";
break;
default:
System.out.println(i+"行"+j+" 列 is default type");
value = cell.toString();
}
if (value == null || "".equals(value)) {
continue;
}
linked.add(value);
}
list.add(linked);
}
return list;
}


package com.dbs.vote.common.test.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFeatures;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class JExcelUtils {

/**
* 生成Excel文件
* @param path 文件路径
* @param sheetName 工作表名称
* @param dataTitles 数据标题
*/
public void createExcelFile(String path,String sheetName,String[] dataTitles){
WritableWorkbook workbook;
try{
OutputStream os=new FileOutputStream(path);
workbook=Workbook.createWorkbook(os);

WritableSheet sheet = workbook.createSheet(sheetName, 0); //添加第一个工作表
initialSheetSetting(sheet);

Label label;
for (int i=0; i<dataTitles.length; i++){
//Label(列号,行号,内容,风格)
label = new Label(i, 0, dataTitles[i],getTitleCellFormat());
sheet.addCell(label);
}

//插入一行
insertRowData(sheet,1,new String[]{"200201001","张三","100","60","100","260"},getDataCellFormat(CellType.STRING_FORMULA));

//一个一个插入行
label = new Label(0, 2,"200201002",getDataCellFormat(CellType.STRING_FORMULA));
sheet.addCell(label);

label = new Label(1, 2,"李四",getDataCellFormat(CellType.STRING_FORMULA));
sheet.addCell(label);

insertOneCellData(sheet,2,2,70.5,getDataCellFormat(CellType.NUMBER));
insertOneCellData(sheet,3,2,90.523,getDataCellFormat(CellType.NUMBER));
insertOneCellData(sheet,4,2,60.5,getDataCellFormat(CellType.NUMBER));

insertFormula(sheet,5,2,"C3+D3+E3",getDataCellFormat(CellType.NUMBER_FORMULA));

//插入日期
mergeCellsAndInsertData(sheet, 0, 3, 5, 3, new Date(), getDataCellFormat(CellType.DATE));

workbook.write();
workbook.close();
}catch(Exception e){
e.printStackTrace();
}
}

/**
* 初始化表格属性
* @param sheet
*/
public void initialSheetSetting(WritableSheet sheet){
try{
//sheet.getSettings().setProtected(true); //设置xls的保护,单元格为只读的
sheet.getSettings().setDefaultColumnWidth(10); //设置列的默认宽度
//sheet.setRowView(2,false);//行高自动扩展
//setRowView(int row, int height);--行高
//setColumnView(int col,int width); --列宽
sheet.setColumnView(0,20);//设置第一列宽度
}catch(Exception e){
e.printStackTrace();
}
}

/**
* 插入公式
* @param sheet
* @param col
* @param row
* @param formula
* @param format
*/
public void insertFormula(WritableSheet sheet,Integer col,Integer row,String formula,WritableCellFormat format){
try{
Formula f = new Formula(col, row, formula, format);
sheet.addCell(f);
}catch(Exception e){
e.printStackTrace();
}
}

/**
* 插入一行数据
* @param sheet 工作表
* @param row 行号
* @param content 内容
* @param format 风格
*/
public void insertRowData(WritableSheet sheet,Integer row,String[] dataArr,WritableCellFormat format){
try{
Label label;
for(int i=0;i<dataArr.length;i++){
label = new Label(i,row,dataArr[i],format);
sheet.addCell(label);
}
}catch(Exception e){
e.printStackTrace();
}
}

/**
* 插入单元格数据
* @param sheet
* @param col
* @param row
* @param data
*/
public void insertOneCellData(WritableSheet sheet,Integer col,Integer row,Object data,WritableCellFormat format){
try{
if(data instanceof Double){
jxl.write.Number labelNF = new jxl.write.Number(col,row,(Double)data,format);
sheet.addCell(labelNF);
}else if(data instanceof Boolean){
jxl.write.Boolean labelB = new jxl.write.Boolean(col,row,(Boolean)data,format);
sheet.addCell(labelB);
}else if(data instanceof Date){
jxl.write.DateTime labelDT = new jxl.write.DateTime(col,row,(Date)data,format);
sheet.addCell(labelDT);
setCellComments(labelDT, "这是个创建表的日期说明!");
}else{
Label label = new Label(col,row,data.toString(),format);
sheet.addCell(label);
}
}catch(Exception e){
e.printStackTrace();
}

}

/**
* 合并单元格,并插入数据
* @param sheet
* @param col_start
* @param row_start
* @param col_end
* @param row_end
* @param data
* @param format
*/
public void mergeCellsAndInsertData(WritableSheet sheet,Integer col_start,Integer row_start,Integer col_end,Integer row_end,Object data, WritableCellFormat format){
try{
sheet.mergeCells(col_start,row_start,col_end,row_end);//左上角到右下角
insertOneCellData(sheet, col_start, row_start, data, format);
}catch(Exception e){
e.printStackTrace();
}

}

/**
* 给单元格加注释
* @param label
* @param comments
*/
public void setCellComments(Object label,String comments){
WritableCellFeatures cellFeatures = new WritableCellFeatures();
cellFeatures.setComment(comments);
if(label instanceof jxl.write.Number){
jxl.write.Number num = (jxl.write.Number)label;
num.setCellFeatures(cellFeatures);
}else if(label instanceof jxl.write.Boolean){
jxl.write.Boolean bool = (jxl.write.Boolean)label;
bool.setCellFeatures(cellFeatures);
}else if(label instanceof jxl.write.DateTime){
jxl.write.DateTime dt = (jxl.write.DateTime)label;
dt.setCellFeatures(cellFeatures);
}else{
Label _label = (Label)label;
_label.setCellFeatures(cellFeatures);
}
}

/**
* 读取excel
* @param inputFile
* @param inputFileSheetIndex
* @throws Exception
*/
public ArrayList<String> readDataFromExcel(File inputFile, int inputFileSheetIndex){
ArrayList<String> list = new ArrayList<String>();
Workbook book = null;
Cell cell = null;
WorkbookSettings setting = new WorkbookSettings();
java.util.Locale locale = new java.util.Locale("zh","CN");
setting.setLocale(locale);
setting.setEncoding("ISO-8859-1");
try{
book = Workbook.getWorkbook(inputFile, setting);
}catch(Exception e){
e.printStackTrace();
}

Sheet sheet = book.getSheet(inputFileSheetIndex);
for (int rowIndex = 0; rowIndex < sheet.getRows(); rowIndex++) {//行
for (int colIndex = 0; colIndex < sheet.getColumns(); colIndex++) {//列
cell = sheet.getCell(colIndex, rowIndex);
//System.out.println(cell.getContents());
list.add(cell.getContents());
}
}
book.close();

return list;
}

/**
* 得到数据表头格式
* @return
*/
public WritableCellFormat getTitleCellFormat(){
WritableCellFormat wcf = null;
try {
//字体样式
WritableFont wf = new WritableFont(WritableFont.TIMES,12, WritableFont.NO_BOLD,false);//最后一个为是否italic
wf.setColour(Colour.RED);
wcf = new WritableCellFormat(wf);
//对齐方式
wcf.setAlignment(Alignment.CENTRE);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
//边框
wcf.setBorder(Border.ALL,BorderLineStyle.THIN);

//背景色
wcf.setBackground(Colour.GREY_25_PERCENT);
} catch (WriteException e) {
e.printStackTrace();
}
return wcf;
}

/**
* 得到数据格式
* @return
*/
public WritableCellFormat getDataCellFormat(CellType type){
WritableCellFormat wcf = null;
try {
//字体样式
if(type == CellType.NUMBER || type == CellType.NUMBER_FORMULA){//数字
NumberFormat nf = new NumberFormat("#.00");
wcf = new WritableCellFormat(nf);
}else if(type == CellType.DATE || type == CellType.DATE_FORMULA){//日期
jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-MM-dd hh:mm:ss");
wcf = new jxl.write.WritableCellFormat(df);
}else{
WritableFont wf = new WritableFont(WritableFont.TIMES,10, WritableFont.NO_BOLD,false);//最后一个为是否italic
wcf = new WritableCellFormat(wf);
}
//对齐方式
wcf.setAlignment(Alignment.CENTRE);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
//边框
wcf.setBorder(Border.LEFT,BorderLineStyle.THIN);
wcf.setBorder(Border.BOTTOM,BorderLineStyle.THIN);
wcf.setBorder(Border.RIGHT,BorderLineStyle.THIN);
//背景色
wcf.setBackground(Colour.WHITE);

wcf.setWrap(true);//自动换行

} catch (WriteException e) {
e.printStackTrace();
}
return wcf;
}

/**
* 打开文件看看
* @param exePath
* @param filePath
*/
public void openExcel(String exePath,String filePath){
Runtime r=Runtime.getRuntime();
String cmd[]={exePath,filePath};
try{
r.exec(cmd);
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args){
String[] titles = {"学号","姓名","语文","数学","英语","总分"};
JExcelUtils jxl = new JExcelUtils();
String filePath = "E:/test.xls";
jxl.createExcelFile(filePath,"成绩单",titles);
jxl.readDataFromExcel(new File(filePath),0);
jxl.openExcel("C:/Program Files/Microsoft Office/OFFICE11/EXCEL.EXE",filePath);
}
}


package excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelReader {

public static List<String[]> readExcel(File excelFile,int rowNum) throws BiffException, IOException{

//创建一个list用来存读取的内容
List<String[]> list =new ArrayList<String[]>();
Workbook rwb = null;
Cell cell = null;

//创建输入流
InputStream stream = new FileInputStream(excelFile);
//获取Excel文件对象
rwb = Workbook.getWorkbook(stream);
//获取文件的指定工作表 默认的第一个
Sheet sheet = rwb.getSheet(0);
//行数(表头的目录不需要,从1开始)
for(int i = rowNum-1;i<sheet.getRows();i++){
//创建一个数组 用来存储每一列的值
String[] str = new String[sheet.getColumns()];
//列数
for(int j =0;j<sheet.getColumns();j++){
//获取第i行,第j列的值
cell = sheet.getCell(j, i);
str[j] = cell.getContents();
}
list.add(str);
}
return list;
}

public static void main(String[] args) {
String excelFileName ="D:\\ExcelDemo.xls";
try{
List<String[]>list = ExcelReader.readExcel(new File(excelFileName), 1);
System.out.println();
for(int i = 0;i< list.size();i++){
String[] str = (String[]) list.get(i);
for(int j = 0;j <str.length; j++){
System.out.println(str[j]);
}
}
}catch(BiffException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}


Cell cell = sheet.getCell(col, row);
if(cell.getType() == CellType.NUMBER){
NumberCell numberCell = (NumberCell) cell;
double value =numberCell.getValue();
}


package com.office;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
//import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
//import java.io.OutputStream;
import java.util.Date;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.read.biff.WorkbookParser;
import jxl.write.Label;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class TestJXL {


public static void main(String[] args) throws RowsExceededException,
WriteException, IOException, BiffException {
String path = "srccomofficetest.xls";
writeDataToExcel(path);
getExcelData(path);

}

// 利用jxl.jar包取excle表格的数据
public static void getExcelData(String path) throws BiffException,
IOException {
InputStream is = new FileInputStream(path);
//Workbook wb = null;
WorkbookParser rwb = (WorkbookParser) WorkbookParser.getWorkbook(is);
System.out.println("获得工作薄中工作表sheet的个数=" + rwb.getNumberOfSheets());
@SuppressWarnings("unused")
Sheet[] sheets = rwb.getSheets();// 返回工作薄(Workbook)中工作表(Sheet)对象数组
Sheet rs = rwb.getSheet(0);
System.out.println("获得sheet的名称=" + rs.getName());
System.out.println("获得sheet中所包含的总列数=" + rs.getColumns());
@SuppressWarnings("unused")
Cell[] cells1 = rs.getColumn(0);// 获取某一列所有的单元格
System.out.println("获得sheet中所包含的总行数=" + rs.getRows());
@SuppressWarnings("unused")
Cell[] cells2 = rs.getRow(0);// 获取某一行的所有单元格

Cell c00 = rs.getCell(0, 0);// 第一个是列数,第二个是行数
String t = c00.getContents();// getContents()将任何类型的Cell值都作为一个字符串返回
System.out.println(t);
if (c00.getType() == CellType.LABEL) {
LabelCell labelc00 = (LabelCell) c00;
String strc00 = labelc00.getString();
System.out.println(strc00);
}
if (c00.getType() == CellType.NUMBER) {
NumberCell number00 = (NumberCell) c00;
double strc00 = number00.getValue();
System.out.println(strc00);
}
if (c00.getType() == CellType.DATE) {
DateCell datec00 = (DateCell) c00;
Date strc00 = datec00.getDate();
System.out.println(strc00);
}
rwb.close();
is.close();
}

// 利用jxl.jar包向excle表格写数据
public static void writeDataToExcel(String path) throws IOException,
RowsExceededException, WriteException {
File file = new File(path);
// 构造Workbook对象,只读Workbook对象
// Method1:创建可写入的excle工作簿
WritableWorkbook wwb1 = Workbook.createWorkbook(file);
// Method2:将WritableWorkbook直接写入到输出流
//OutputStream os = new FileOutputStream(path);
//WritableWorkbook wwb2 = Workbook.createWorkbook(os);
// 创建Excel工作表
WritableSheet ws = wwb1.createSheet("测试", 0);//arg0,表示sheet的名称,arg1表示第几个sheet,下标从0开始

//设置列的宽度、设置行的高度 jxl中20个高度对应excel的1个高度,jxl的1个宽度对应excel的7个宽度
ws.getSettings().setDefaultColumnWidth(25); //设置列宽,所有列
ws.getSettings().setDefaultRowHeight(600); //设置行高,所有行

ws.setColumnView(0, 20);//设置列宽,第一个参数为第几列,第二个参数为列宽
ws.setRowView(0, 800);//设置行高,第一个参数为第几行,第二个参数为行高

//是否显示网格 默认为true显示网格
ws.getSettings().setShowGridLines(true);

// (1)添加Label对象
Label labelC = new Label(0, 0, "Label单元格");
ws.addCell(labelC);

// (2) 创建带有字型Formatting的对象
WritableFont wf = new WritableFont(WritableFont.TIMES, 18,
WritableFont.BOLD, true);
WritableCellFormat wcfF = new WritableCellFormat(wf);
//下面Label构造函数参数意思依次为:列数、行数、要写入的内容、这个Label的样式(可选)
Label labelCF = new Label(1, 0, "创建带有字型Formatting的对象", wcfF);
ws.addCell(labelCF);

// (3)创建带有字体颜色Formatting的对象
WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
Colour.RED);
WritableCellFormat wcfFC = new WritableCellFormat(wfc);
wcfFC.setAlignment(jxl.format.Alignment.LEFT);//设置水平对齐方式为居中
wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//把垂直对齐方式指定为居中
wcfFC.setWrap(true);//设置自动换行
Label labelCFC = new Label(2, 0, "创建带有字体颜色Formatting的对象", wcfFC);
ws.addCell(labelCFC);

// (4)添加Number对象
NumberFormat nf = new NumberFormat("#.##");//构造函数的#.##表示保留两位小数
WritableCellFormat wcfN = new WritableCellFormat(nf);
jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
ws.addCell(labelNF);

// (5)添加Boolean对象
jxl.write.Boolean labelB = new jxl.write.Boolean(0, 2, false);//参数依次为:列数、行数、值
ws.addCell(labelB);

// (6)添加DateTime对象
jxl.write.DateTime labelDT = new jxl.write.DateTime(0, 3,
new java.util.Date());
ws.addCell(labelDT);

// (7)添加带有formatting的DateFormat对象
jxl.write.DateFormat df = new jxl.write.DateFormat(
"dd MM yyyy hh:mm:ss");//设置日期的格式
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(
df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(1, 3,
new java.util.Date(), wcfDF);
ws.addCell(labelDTF);

//(8)添加图片 只支持PNG格式的图片
File image=new File("srccomoffice1.png");
//前两位是起始格,后两位是图片占多少个格,并非是位置,四个参数的类型都是double,依次是 x, y, width, height,注意,
//这里的宽和高可不是图片的宽和高,而是图片所要占的单位格的个数
WritableImage wimage=new WritableImage(3,6,4,8,image);
ws.addImage(wimage);

//(10)添加批注
Label labelStr=new Label(1,10,"");


//合并单元格
ws.mergeCells(3, 0, 5, 0);// 合并第一行的第4列到第6列 水平方向
ws.mergeCells(3, 1, 3, 5);//合并第4列的的第二行到第六行 垂直方向
ws.mergeCells(1, 6, 2, 9);

// 设置边框
jxl.write.WritableCellFormat wcsB=new jxl.write.WritableCellFormat ();
wcsB.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.DOUBLE);
wcsB.setBackground(Colour.GREEN);//背景色
Label border=new Label(1,4,"边框设置",wcsB);
ws.addCell(border);

//通过公司求值 暂时还有问题
// NumberFormat nf1 = new NumberFormat("#");
// WritableCellFormat wcfN1 = new WritableCellFormat(nf1);
// jxl.write.Number a = new jxl.write.Number(0, 6, 3, wcfN1);
// jxl.write.Number b = new jxl.write.Number(0, 7,2, wcfN1);
// ws.addCell(a);
// ws.addCell(b);
// Formula l3 = new Formula(0,8,"=SUM(A7:A8)");
// WritableCell cell = l3.copyTo(0, 8);
// ws.addCell(cell);


// 写入excle工作表
wwb1.write();
System.out.println("利用jxl向excle写入数据完成");

// 关闭excle工作簿对象
wwb1.close();

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值