package com.mfanw.ssh.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExcelUtil {
/**
* 根据路径加载excel文件
*
* @param xlsPath
* 文件路径
* @param startRow
* 开始的行号(从0开始)
* @param startCount
* 开始的列号 (从0开始)
* @param endCount
* 结束的列号 (从0开始)
* @return 结果集合
*/
public ArrayList<String[]> excelRead(String xlsPath, int startRow, int startCount, int endCount) {
ArrayList<String[]> result = new ArrayList<String[]>();
Sheet sheet = null;
InputStream is = null;
Workbook wb = null;
try {
is = new FileInputStream(xlsPath);// 工作簿需要是标准的工作簿
wb = Workbook.getWorkbook(is); // 得到工作薄,全部工作簿
String[] lineContent = null;
sheet = wb.getSheet(0);
int rows = sheet.getRows(); // 得到excel的总行数
for (int row = startRow; row < rows; row++) {// 4是为了定位到输入的开始位置
lineContent = new String[endCount - startCount];
for (int count = startCount; count < endCount; count++) {
lineContent[count - startCount] = getCellString(sheet, count, row);
}
result.add(lineContent);
}
wb.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
wb.close();
is.close();
} catch (Exception e) {
}
}
return result;
}
/**
*
* @param sheet
* @param x
* @param y
* @return
*/
private String getCellString(Sheet sheet, int x, int y) {
String s = "";
try {
s = sheet.getCell(x, y).getContents().trim();
} catch (Exception e) {
s = "";
}
return s;
}
public void excelWrite(OutputStream os, ArrayList<String[]> result, String sheetName) throws Exception {
WritableWorkbook workbook = Workbook.createWorkbook(os);
WritableSheet sheet = workbook.createSheet(sheetName, 0);
for (int i = 0; i < result.size(); i++) {
String[] temp = result.get(i);
for (int j = 0; j < temp.length; j++) {
Label labelC = new Label(j, i, temp[j]);
sheet.addCell(labelC);
}
}
workbook.write();
workbook.close();
}
public void excelExport(HttpServletResponse response, File file, boolean isDel) throws Exception {
// 获得文件名
String filename = file.getName();
// 定义输出类型(下载)
response.setContentType("application/force-download");
response.setHeader("Location", filename);
// 定义输出文件头
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
OutputStream out = response.getOutputStream();
this.excelWrite(out, null, filename);
out.close();
response.flushBuffer();
if (isDel) {
// 删除文件,删除前关闭所有的Stream.
file.delete();
}
}
public static void main(String[] args) throws Exception {
ExcelUtil util = new ExcelUtil();
ArrayList<String[]> result = util.excelRead("E:/1.xls", 2, 0, 6);
File f = new File("E:/2.xls");
OutputStream os = new FileOutputStream(f);
util.excelWrite(os, result, "22");
os.close();
}
}