java操作excel

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.text.SimpleDateFormat;

import java.util.Date;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import jxl.Cell;

import jxl.Sheet;

import jxl.Workbook;

import jxl.format.Alignment;

import jxl.format.Border;

import jxl.format.Colour;

import jxl.format.UnderlineStyle;

import jxl.format.VerticalAlignment;

import jxl.write.DateFormat;

import jxl.write.DateTime;

import jxl.write.Label;

import jxl.write.NumberFormat;

import jxl.write.WritableCellFormat;

import jxl.write.WritableFont;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;


public class OperationExcel_1 extends ActionSupport {

HttpServletResponse response = ServletActionContext.getResponse();

HttpServletRequest request = ServletActionContext.getRequest();

private static final int BUFFER_SIZE = 800 * 1024;// 一次性可读最大字节

private File myfile;// 上传文件域对象

private String myfileContentType;// 文件类型

private String myfileFileName;// 上传文件名

private String savePath;// 保存路径

private String keyword;


//导出excel

public String execute() {

try {

// 获得输出流,该输出流的输出介质是客户端浏览器

OutputStream output = response.getOutputStream();

// 清除首部的空白行

// getResponse的getWriter()方法连续两次输出流到页面的时候,第二次的流会包括第一次的流,所以可以使用response.reset或者resetBuffer的方法。

response.reset();


// 导出时默认的名字,解决汉字问题

String filename = "学员考试成绩一览表.xls";

filename = new String(filename.getBytes("GB2312"), "ISO_8859_1");

response.setHeader("Content-disposition", "attachment;filename="

+ filename);


response.setContentType("application/msexcel");


// 创建可写入的excel工作薄,且内容将写入到输出流,并通过输出流输出给客户端浏览器

WritableWorkbook wk = Workbook.createWorkbook(output);


WritableSheet sheet = wk.createSheet("成绩表", 0);


// 设置行高

sheet.setRowView(0, 15);

// 设置列宽

sheet.setColumnView(4, 30);

// mergeCells(column,row,column1,row1)把单元格(column,row)到单元格(column1,row1)进行合并

// 单元格合并方法

sheet.mergeCells(0, 0, 4, 0);


// 创建writableFont字体对象,参数依次表示黑体、字号12、粗体、非斜体、不带下划线、亮蓝色

WritableFont titleFont = new WritableFont(

WritableFont.createFont("黑体"), 12, WritableFont.BOLD,

false, UnderlineStyle.NO_UNDERLINE, Colour.LIGHT_BLUE);


// 创建writablecellformat对象,将该对象应用于单元格从而设置单元格的样式

WritableCellFormat titleFormat = new WritableCellFormat();


// 设置字体格式

titleFormat.setFont(titleFont);

// 设置文本水平居中对齐

titleFormat.setAlignment(Alignment.CENTRE);

// 设置文本垂直居中对齐

titleFormat.setVerticalAlignment(VerticalAlignment.CENTRE);

// 设置背景颜色

titleFormat.setBackground(Colour.GRAY_25);

// 设置自动换行

titleFormat.setWrap(true);

// 添加Label对象,参数依次表示第一列,第一行,内容,使用的格式

Label lab_00 = new Label(0, 0, "学员考试成绩一览表", titleFormat);


// 将定义好的Label对象添加到工作表上,这样工作表的第一列第一行的内容为‘学员考试成绩一览表’并应用了titleFormat定义的样式

sheet.addCell(lab_00);


WritableCellFormat cloumnTitleFormat = new WritableCellFormat();

cloumnTitleFormat.setFont(new WritableFont(WritableFont

.createFont("宋体"), 10, WritableFont.BOLD, false));

cloumnTitleFormat.setAlignment(Alignment.CENTRE);


Label lab_01 = new Label(0, 1, "姓名", cloumnTitleFormat);

Label lab_11 = new Label(1, 1, "班级", cloumnTitleFormat);

Label lab_21 = new Label(2, 1, "笔试成绩", cloumnTitleFormat);

Label lab_31 = new Label(3, 1, "上机成绩", cloumnTitleFormat);

Label lab_41 = new Label(4, 1, "考试日期", cloumnTitleFormat);

sheet.addCell(lab_01);

sheet.addCell(lab_11);

sheet.addCell(lab_21);

sheet.addCell(lab_31);

sheet.addCell(lab_41);


sheet.addCell(new Label(0, 2, "李明"));

sheet.addCell(new Label(1, 2, "As178"));

/*sheet.addCell(new Label(0, 3, "哈哈"));

sheet.addCell(new Label(1, 3, "As179"));*/

// 定义数字格式

NumberFormat nf = new NumberFormat("###,##0.00");

WritableCellFormat wcf = new WritableCellFormat(nf);

// 设置边框线

wcf.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);

// 类似于Label对象,区别lable表示文本数据,number表示数值型数据

jxl.write.Number numlab_22 = new jxl.write.Number(2, 2, 78, wcf);

/*jxl.write.Number numlab_23 = new jxl.write.Number(2, 3, 89, wcf);*/

sheet.addCell(numlab_22);

/*sheet.addCell(numlab_23);*/

sheet.addCell(new jxl.write.Number(3, 2, 87,

new WritableCellFormat(new NumberFormat("###,##0.00"))));

/*sheet.addCell(new jxl.write.Number(3, 3, 98,

new WritableCellFormat(new NumberFormat("###,##0.00"))));*/

// 定义日期格式

DateFormat df = new DateFormat("yyyy-MM-dd hh:mm:ss");

// 创建WritableCellFormat对象

WritableCellFormat datewcf = new WritableCellFormat(df);

// 类似于Label对象,区别lable表示文本数据,DateTime表示日期型数据

DateTime dtLab_42 = new DateTime(4, 2, new Date(), datewcf);

sheet.addCell(dtLab_42);

/*DateTime dtLab_43 = new DateTime(4, 3, new Date(), datewcf);

sheet.addCell(dtLab_43);*/

/*

 * // 设置页眉页脚 HeaderFooter hf = new HeaderFooter();

 * hf.getLeft().append("嘿嘿"); hf.getCentre().append("哈哈");

 * hf.getRight().append("呵呵"); // 加入页眉

 * sheet.getSettings().setHeader(hf); // 加入页脚

 * sheet.getSettings().setFooter(hf); sheet.mergeCells(5,2, 6,2); //

 * F:\picture File imgFile = new

 * File("F:/picture/QQ截图20130327162721.png"); WritableImage img =

 * new WritableImage(5, 2,1,1, imgFile); sheet.addImage(img);

 */


// 将定义的工作表输出到之前指定的介质中

wk.write();

// 操作完成时,关闭对象,

wk.close();

} catch (IOException e) {

e.printStackTrace();

} catch (RowsExceededException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

return SUCCESS;

}


//导入excel

public String importexcel() {

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式

// 以当前时间重新命名

String filename = df.format(new Date())

+ getExtention(this.getMyfileFileName());

// 目标文件路径

String dstPath = ServletActionContext.getServletContext().getRealPath(

this.getSavePath())

+ "\\" + filename;

File dstFile = new File(dstPath);


// 读入

copy(this.myfile, dstFile);

setMyfileFileName(filename);


//String s=readExcel(dstFile);

//System.out.println(s);

boolean b=searchKeyWord(dstFile,getKeyword());

System.out.println(getKeyword());

System.out.println(b);

return SUCCESS;

}


//读取excel

public static String readExcel(File file){

StringBuffer sb=new StringBuffer();

Workbook wb=null;

try {

//构造Workbook(工作薄)对象

wb=Workbook.getWorkbook(file);

} catch (Exception e) {

e.printStackTrace();

}


if(wb==null)return null;


//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了

Sheet[] sheet=wb.getSheets();


if(sheet!=null&&sheet.length>0){

//对每个工作表进行循环

for(int i=0;i<sheet.length;i++){

//得到当前工作表的行数

int rowNum=sheet[i].getRows();

for(int j=0;j<rowNum;j++){

//得到当前行的所有单元格

Cell[] cells=sheet[i].getRow(j);

if(cells!=null&&cells.length>0){

//对每个单元格进行循环

for(int k=0;k<cells.length;k++){

//读取当前单元格的值

String cellValue=cells[k].getContents();

sb.append(cellValue+"");

}

}

sb.append(" "+"\n");

}

sb.append(" ");

}

}

wb.close();

return sb.toString();

}


// 复制

private static void copy(File src, File dst) {

try {

InputStream in = null;

OutputStream out = null;

try {

in = new BufferedInputStream(new FileInputStream(src),

BUFFER_SIZE);// 输入流

out = new BufferedOutputStream(new FileOutputStream(dst),

BUFFER_SIZE);// 输出流


byte[] buffer = new byte[BUFFER_SIZE];

// 一次性读最大字节并写入

while (in.read(buffer) > 0) {

out.write(buffer);

}

} finally {

if (null != in) {

in.close();// 关闭输入流

}

if (null != out) {

out.close();// 关闭输出流

}

}

} catch (Exception e) {

e.printStackTrace();

}

}


//截取后缀名

// 截取后缀名

private static String getExtention(String fileName) {

int pos = fileName.lastIndexOf(".");

return fileName.substring(pos);

}


//搜索某个excel文件中是否包含某一个关键字

public static boolean searchKeyWord(File file,String keyWord){

boolean res=false;


Workbook wb=null;

try {

//构造Workbook(工作薄)对象

wb=Workbook.getWorkbook(file);

} catch (Exception e) {

e.printStackTrace();

return res;

}


if(wb==null)return res;

//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了

Sheet[] sheet=wb.getSheets();


boolean breakSheet=false;


if(sheet!=null&&sheet.length>0){

//对每个工作表进行循环

for(int i=0;i<sheet.length;i++){

if(breakSheet)break;

//得到当前工作表的行数

int rowNum=sheet[i].getRows();


boolean breakRow=false;


for(int j=0;j<rowNum;j++){

if(breakRow)break;

//得到当前行的所有单元格

Cell[] cells=sheet[i].getRow(j);

if(cells!=null&&cells.length>0){

boolean breakCell=false;

//对每个单元格进行循环

for(int k=0;k<cells.length;k++){

if(breakCell)break;

//读取当前单元格的值

String cellValue=cells[k].getContents();

if(cellValue==null)

continue;

if(cellValue.contains(keyWord)){

res=true;

breakCell=true;

breakRow=true;

breakSheet=true;

}

}

}

}

}

}

//最后关闭资源,释放内存

wb.close();

return res;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值