- Maven项目添加依赖(其它项目自行导入jar包):
<!-- POI依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2.编写代码
package my.diyijie;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
/**
* Created by Administrator on 2019/4/9/009.
*/
public class myDaoChuExsl {
public static void main(String[] args) {
InputStream is = null;
try {
is = new FileInputStream("D:\\cheshi.xls");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 新建一输出文件流
OutputStream fOut = null;
try {
fOut = new BufferedOutputStream(new FileOutputStream("D:\\cheshi2.xls"));
} catch (IOException e) {
e.printStackTrace();
}
HSSFWorkbook book = null;
try {
// book = new XSSFWorkbook(fileInputStream);
book = new HSSFWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
}
// 设置样式;
HSSFCellStyle style = getStyle(book);
//获取第一个sheet
HSSFSheet sheet = book.getSheetAt(0);
HSSFCell cell = null;
// 新建一行,在表格中显示为第二行
HSSFRow row = sheet.createRow(1);
//第一个单元格
cell = row.createCell(0);
//为单元格设置值
cell.setCellValue("hahahhaha");
//为单元格设置样式
cell.setCellStyle(style);
//第二个单元格
cell = row.createCell(1);
cell.setCellValue("hahahhaha");
cell.setCellStyle(style);
try {
book.write(fOut);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*方法功能:导出Excel数据表格样式
*/
public static HSSFCellStyle getStyle(HSSFWorkbook book){
// 设置字体
Font font = book.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 11);
// 字体加粗
// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 设置字体名字
font.setFontName("宋体");
// 设置样式;
HSSFCellStyle style = book.createCellStyle();
// 设置底边框;
style.setBorderBottom(BorderStyle.THIN);
// 设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
// 设置左边框;
style.setBorderLeft(BorderStyle.THIN);
// 设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
// 设置右边框;
style.setBorderRight(BorderStyle.THIN);
// 设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
// 设置顶边框;
style.setBorderTop(BorderStyle.THIN);
// 设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
// 在样式用应用设置的字体;
style.setFont(font);
// 设置自动换行;
style.setWrapText(true);
// 水平居中
style.setAlignment(HorizontalAlignment.CENTER);
//垂直居中
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}
- web上下载把输出流改为response.getOutputStream(),并加上这段代码。
response.reset(); response.setContentType("application/vnd.ms-excel"); response.setHeader("content-disposition", "attachment;filename=\"文件名\"");