java实现对Excel文件的操作主要是通过POI来实现的
1. POI简介
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。更多详情可以[百度](http://www.baidu.com)
基本功能:
HSSF - 提供读写Microsoft Excel格式档案(.xls)的功能。
XSSF - 提供读写Microsoft Excel OOXML格式档案(.xlsx)的功能。
HWPF - 提供读写Microsoft Word格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读写Microsoft Visio格式档案的功能。
2. 使用poi创建excel文件
2.1 创建Excel文档演示如何利用Jakarta POI API 创建Excel 文档。(百度百科示例的修改版)
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateXL {
/** Excel 文件要存放的位置,假定在D盘下*/
public static String outputFile = "D:/test.xls";
public static void main(String argv[]) {
new CreateXL().createExcelFile("test1","xls");
new CreateXL().createExcelFile("test1","xlsx");
}
public void createExcelFile(String proFileName,String suffix){
String fileName = proFileName+"."+suffix;
String path = "D:/"+fileName;
Workbook workbook = null;
if("xls".equals(suffix)){
// 创建新的Excel97-2003 工作簿
workbook = new HSSFWorkbook();
}else if("xlsx".equals(suffix)){
// 创建新的ExcelOOXML格式工作簿
workbook = new XSSFWorkbook();
}else{
System.out.println("无后缀名");
return ;
}
//创建工作表,xls后缀为HSSFSheet,xlsx为XSSFSheet
Sheet sheet = workbook.createSheet();
// 在索引0的位置创建行(最顶端的行),xls后缀为HSSFRow,xlsx为XSSFRow
Row row = sheet.createRow(0);
//在索引0的位置创建单元格(左上端),xls后缀为HSSFCell,xlsx为XSSFCell
Cell cell = row.createCell(0);
// 定义单元格为字符串类型,xls后缀为HSSFCell.CELL_TYPE_STRING,xlsx为XSSFCell.CELL_TYPE_STRING
cell.setCellType(Cell.CELL_TYPE_STRING);
// 在单元格中输入一些内容
cell.setCellValue("增加值");
//在单元格中显示不同的字体
// String[] subStr = {
// "first", "second"
// };
// Font ftRed = workbook.createFont();
// ftRed.setColor(Font.COLOR_RED);
// Font ftBlue = workbook.createFont();
// ftBlue.setColor(HSSFColor.BLUE.index);
// String [] subStr = {"first","second"};
// String sText = subStr[0] + "," + subStr[1];
// HSSFRichTextString textString = new HSSFRichTextString(sText);
// textString.applyFont(
// sText.indexOf(subStr[0]),
// sText.indexOf(subStr[0]) + subStr[0].length(),
// ftRed
// );
// textString.applyFont(
// sText.indexOf(subStr[1]),
// sText.indexOf(subStr[1]) + subStr[1].length(),
// ftBlue
// );
// cell.setCellValue(textString);
//创建文本样式
CellStyle style = workbook.createCellStyle();
//设置边框
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//文字换行
style.setWrapText(true);
//字体
Font font = workbook.createFont();
//文字大小
font.setFontHeightInPoints((short) 12);
font.setFontName("黑体");
font.setColor(Font.COLOR_RED);
style.setFont(font);
cell.setCellStyle(style);
// 新建一输出文件流
FileOutputStream fOut;
try {
fOut = new FileOutputStream(path);
workbook.write(fOut);
fOut.flush();
// 操作结束,关闭文件
fOut.close();
System.out.println("文件生成...");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 把相应的Excel 工作簿存盘
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.2 POI操作现有本地Excel
public void changeLocalExcel(){
//找到该类同文件夹下的文件,getResource("")是得到该类.class文件的URL
//getResource("/")是得到该类.class文件根目录的URL,web项目一般为.../WEB_INF/classes
//得到文件的输入流
InputStream fis = CreateXL.class.getResourceAsStream("local1.xlsx");
//或者
// try {
// InputStream fs = new FileInputStream("local1.xlsx");
// POIFSFileSystem ps =new POIFSFileSystem(fs);
// Workbook workbook = new HSSFWorkbook(ps);
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
XSSFWorkbook workbook = null;
try {
//将输入流作为参数传入Workbook构造函数
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
//在excel文件最后一行后创建行
XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
XSSFCell idCell = dataRow.createCell(0);
//............各种操作
if(workbook!=null){
//输出到文件
FileOutputStream fos =new FileOutputStream("local1.xlsx");
workbook.write(fos);
fos.flush();
fos.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
3. 浏览器文件下载功能实现:
//下载文件功能
public String downHistoryExport(String fileName){
//
try {
String excelFile = fileName;
String localFilePath = "/ExcelExport/"+excelFile;
//如果文件名参数是中文,且通过url传参,需要转换编码方式,gb2312也可换成GBK
String iso_excelFile = new String( excelFile.getBytes("gb2312"), "ISO8859-1" );
HttpServletResponse response = getResponse();
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;fileName=\"" + iso_excelFile+"\"");
ServletOutputStream out = null;
InputStream inputStream = ServletActionContext.getServletContext().getResourceAsStream(localFilePath);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[100];
int count = -1;
while ((count = inputStream.read(data, 0, 100)) != -1) {
outStream.write(data, 0, count);
}
out = response.getOutputStream();
outStream.writeTo(out);
out.flush();
outStream.flush();
return null;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
3.1 注意事项
(1) 在Struts2框架下的getRequest()和getReaponse()方法,需要类中继承ActionSupport(com.opensymphony.xwork2.ActionSupport)
protected HttpServletRequest getRequest() {
return Struts2Utils.getRequest();
}
protected HttpServletResponse getResponse() {
return Struts2Utils.getResponse();
}
protected HttpSession getHttpSession() {
return Struts2Utils.getSession();
}
(2) 不能通过AJAX直接链接下载的URL,因为AJAX不会处理返回的下载内容,需要用浏览器链接下载的URL,在js文件中用window.open(url)
,如果用url传中文参数,需要转码var url = encodeURI("....含中文的url....")