批量导出数据和全部导出到Excel(详细)和mybatis 中 Foreach的用法

本人这里用的是:SSM(Spring + SpringMVC + Maven) ,话不多说直接步入正题!!!!

首先需要POM包:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.9</version>
</dependency>

java后端代码:

/**
* 批量导出
* @param ids   前端选中的数据
* @param response   相应
* @param request    请求
*/
@RequestMapping("exportExcelTableman")
@ResponseBody
public void exportExcelTableman(String ids, HttpServletResponse response,HttpServletRequest request){

    //去数据库查询 sql我会在下面贴出来(这里我用的是直接在sql里面循环每条数据,也可以在业务层循环查询都是一样的)
    List list = login_Service.stuPois(ids);

    //定义一个String数组  用来设置标题,具体情况根据自己的实际情况来!
    String[] rowName ={"ID","名称","性别","时间","爱好"};
    List<Object[]> datalist = new ArrayList<Object[]>();
    for (int i = 0; i < list.size(); i++) {
    LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) list.get(i);
    Object[] array = map.values().toArray();
    datalist.add(array);
    }


    ExportExcel exporExcel = new ExportExcel("学生表", rowName, datalist, response);

    try {

    exporExcel.export();

    } catch (Exception e) {
    e.printStackTrace();
    }
}

service层需要分割一下,按逗号分割,因为是多个:

@Override
public List stuPois(String ids) {
return mapperLogin.stuPois(ids.split(","));
}

Dao层:

List stuPois(String[] split);

<!-- 批量导出Ex -->  <!--resultType  这个是返回值类型 很基础的知识不懂得可以百度看看-->
<select id="stuPois" resultType="java.util.LinkedHashMap" >
   SELECT * FROM dml_sd where id in
   <foreach collection="array" item="item" open="(" separator=","
      close=")">
      #{item}
   </foreach>
</select>

<!--

   <foreach collection="array" item="item" open="(" separator=","
         close=")">
         #{item}
    </foreach>

-->

这里需要注意下:——————————————————————————————————————————————————————————————————————

   foreach元素的属性主要有 item,index,collection,open,separator,close。

    item 表示集合中每一个元素进行迭代时的别名,
    index 指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
    open 表示该语句以什么开始,
    separator 表示在每次进行迭代之间以什么符号作为分隔 符,
    close 表示以什么结束。

在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:

    1. 如果传入的是单参数且参数类型是一个 List 的时候,collection属性值为list
    2. 如果传入的是单参数且参数类型是一个 array 数组的时候,collection的属性值为array
    3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在breast里面也是会把它封装成一个           Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key 下面分别来看看上述三种情况的示例代码:
    

1.单参数List的类型:

  <select id="dynamicForeachTest" resultType="Blog"  parameterType="java.util.List">
          select * from t_blog where id in
       <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
               #{item}       
       </foreach>    
   </select>

若传入的是List<String>类型 在Mapper文件中处理过后,SQL如下:(直接引用注解中的参数名字,这样mybatis会忽略类型,按名字引入)

<select id="dynamicForeachTest" resultType="Blog">
          select * from t_blog where id in
       <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
               #{item}       
       </foreach>    
   </select>

   上述collection的值为list,对应的Mapper是这样的
   public List dynamicForeachTest(List ids);

  若是传入的是的是List<String>类型的  可能会报出两个参数的异常,这时我们可以用Mybatis官方的注解@Param

  public List dynamicForeachTest(@Param("ids")List<String> ids);

  

测试代码:
      @Test
    public void dynamicForeachTest() {
        SqlSession session = Util.getSqlSessionFactory().openSession();      
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);
         List ids = new ArrayList();
         ids.add(1);
         ids.add(3);
          ids.add(6);
        List blogs = blogMapper.dynamicForeachTest(ids);
         for (Blog blog : blogs)
             System.out.println(blog);
         session.close();
     }

2.单参数array数组的类型

<select id="dynamicForeach2Test" resultType="Blog">
          select * from t_blog where id in
            <foreach collection="array" index="index" item="item" open="(" separator="," close=")">

            #{item}
            </foreach>
     </select>
上述collection为array,对应的Mapper代码:
public List dynamicForeach2Test(int[] ids);

对应的测试代码:
      @Test
    public void dynamicForeach2Test() {
        SqlSession session = Util.getSqlSessionFactory().openSession();
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);
        int[] ids = new int[] {1,3,6,9};
        List blogs = blogMapper.dynamicForeach2Test(ids);
        for (Blog blog : blogs)
        System.out.println(blog);    
        session.close();
      }
    

3.自己把参数封装成Map的类型
<select id="dynamicForeach3Test" resultType="Blog">
        select * from t_blog where title like "%"#{title}"%" and id in
         <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
              #{item}
         </foreach>
    </select>
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
public List dynamicForeach3Test(Map params);

对应测试代码:


      @Test
    public void dynamicForeach3Test() {
        SqlSession session = Util.getSqlSessionFactory().openSession();
         BlogMapper blogMapper = session.getMapper(BlogMapper.class);
          final List ids = new ArrayList();
          ids.add(1);
          ids.add(2);
          ids.add(3);
          ids.add(6);
         ids.add(7);
         ids.add(9);
        Map params = new HashMap();
         params.put("ids", ids);
         params.put("title", "中国");
        List blogs = blogMapper.dynamicForeach3Test(params);
         for (Blog blog : blogs)
             System.out.println(blog);
         session.close();
     }
——————————————————————————————————————————————————————————————————————————————

下面是工具类 ExportExcel:

/**
* 导出Excel公共方法
* @version 1.0
*
* @author wangcp
*
*/
public class ExportExcel {

//显示的导出表的标题
private String title;
//导出表的列名
private String[] rowName ;

private List<Object[]> dataList = new ArrayList<Object[]>();

HttpServletResponse response;

//构造方法,传入要导出的数据
public ExportExcel(String title,String[] rowName,List<Object[]> dataList, HttpServletResponse response){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
this.response = response;
}

/*
* 导出数据
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 03版excel
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);

//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】 ---------------------------------
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyleFole(workbook); //单元格样式对象
HSSFCellStyle hei=this.getStylehah(workbook);
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);

// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)

// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}

//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){

Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数

for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
// if(j == 0){
// cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
// cell.setCellValue(i+1);
// }else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}else{
cell.setCellValue("无");
}
// }
if((j+1)%2==0){
cell.setCellStyle(hei);
}else{
cell.setCellStyle(style); //设置单元格样式
}
if((i+1)%2==1){
cell.setCellStyle(hei);
}else{

cell.setCellStyle(style); //设置单元格样式
}
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = 0;
if (null != currentCell.getStringCellValue() && !"".equals(currentCell.getStringCellValue())) {
length = currentCell.getStringCellValue().getBytes().length;
}

if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}

if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}

}catch(Exception e){
e.printStackTrace();
}

}

/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setFillForegroundColor(HSSFColor.LAVENDER.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

return style;

}

/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//背景颜色
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 填充单元格
style.setFillForegroundColor(HSSFColor.YELLOW.index);
//style.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
//设置底边框;

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setRightBorderColor(HSSFColor.RED.index);

style.setFillForegroundColor(HSSFColor.LAVENDER.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

return style;

}

public HSSFCellStyle getStylehah(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(HSSFColor.RED.index);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setRightBorderColor(HSSFColor.RED.index);

return style;

}

public HSSFCellStyle getStyleFole(HSSFWorkbook workbook) {
HSSFCellStyle cell_Style = (HSSFCellStyle) workbook .createCellStyle();// 设置字体样式
cell_Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell_Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直对齐居中
cell_Style.setWrapText(true); // 设置为自动换行
HSSFFont cell_Font = (HSSFFont) workbook.createFont();
cell_Font.setFontName("宋体");
cell_Font.setFontHeightInPoints((short) 8);
cell_Style.setFont(cell_Font);
cell_Style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cell_Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
cell_Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
cell_Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
cell_Style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
cell_Style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cell_Style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 边框
cell_Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cell_Style.setBorderRight(HSSFCellStyle.BORDER_THIN);
cell_Style.setBorderTop(HSSFCellStyle.BORDER_THIN);
cell_Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
return cell_Style;
}

}

——————————————————————————————————————————————————————————————————————————————

 

以上就是选中批量导出全部后台代码那么全部导出呢?其实就少了一步循环其余的都不变,上代码!!!

——————————————————————————————————————————————————————————————————————————————

/**
* 全部导出
*/
@RequestMapping("exportExcelTable")
@ResponseBody
public void exportExcelTable(HttpServletResponse response,HttpServletRequest request){
List list = login_Service.stuPoi();
String[] rowName ={"ID","名称","性别","时间","爱好"};
List<Object[]> datalist = new ArrayList<Object[]>();
for (int i = 0; i < list.size(); i++) {
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) list.get(i);
Object[] array = map.values().toArray();
datalist.add(array);
}
ExportExcel exporExcel = new ExportExcel("学生表", rowName, datalist, response);

try {

exporExcel.export();
} catch (Exception e) {
e.printStackTrace();
}
}

service层

@Override
public List stuPoi() {

return mapperLogin.stuPoi();
}

Dao层

List stuPoi();

sql:

<!-- 导出全部  查询全部 -->
<select id="stuPoi" resultType="java.util.LinkedHashMap" >
SELECT * FROM dml_sd t 
</select>

工具类:

/**
* 导出Excel公共方法
* @version 1.0
*
* @author wangcp
*
*/
public class ExportExcel {

//显示的导出表的标题
private String title;
//导出表的列名
private String[] rowName ;

private List<Object[]> dataList = new ArrayList<Object[]>();

HttpServletResponse response;

//构造方法,传入要导出的数据
public ExportExcel(String title,String[] rowName,List<Object[]> dataList, HttpServletResponse response){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
this.response = response;
}

/*
* 导出数据
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 03版excel
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);

//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】 ---------------------------------
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyleFole(workbook); //单元格样式对象
HSSFCellStyle hei=this.getStylehah(workbook);
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);

// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)

// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}

//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){

Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数

for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
// if(j == 0){
// cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
// cell.setCellValue(i+1);
// }else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}else{
cell.setCellValue("无");
}
// }
if((j+1)%2==0){
cell.setCellStyle(hei);
}else{
cell.setCellStyle(style); //设置单元格样式
}
if((i+1)%2==1){
cell.setCellStyle(hei);
}else{

cell.setCellStyle(style); //设置单元格样式
}
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = 0;
if (null != currentCell.getStringCellValue() && !"".equals(currentCell.getStringCellValue())) {
length = currentCell.getStringCellValue().getBytes().length;
}

if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}

if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}

}catch(Exception e){
e.printStackTrace();
}

}

/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setFillForegroundColor(HSSFColor.LAVENDER.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

return style;

}

/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//背景颜色
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 填充单元格
style.setFillForegroundColor(HSSFColor.YELLOW.index);
//style.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);
//设置底边框;

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setRightBorderColor(HSSFColor.RED.index);

style.setFillForegroundColor(HSSFColor.LAVENDER.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

return style;

}

public HSSFCellStyle getStylehah(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(HSSFColor.RED.index);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setRightBorderColor(HSSFColor.RED.index);

return style;

}

public HSSFCellStyle getStyleFole(HSSFWorkbook workbook) {
HSSFCellStyle cell_Style = (HSSFCellStyle) workbook .createCellStyle();// 设置字体样式
cell_Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell_Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直对齐居中
cell_Style.setWrapText(true); // 设置为自动换行
HSSFFont cell_Font = (HSSFFont) workbook.createFont();
cell_Font.setFontName("宋体");
cell_Font.setFontHeightInPoints((short) 8);
cell_Style.setFont(cell_Font);
cell_Style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cell_Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
cell_Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
cell_Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
cell_Style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
cell_Style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cell_Style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 边框
cell_Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cell_Style.setBorderRight(HSSFCellStyle.BORDER_THIN);
cell_Style.setBorderTop(HSSFCellStyle.BORDER_THIN);
cell_Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
return cell_Style;
}


}

方法二:

@RequestMapping("aaaa")
@ResponseBody
public void loglist(){
String title = "测试";
String[] rowName ={"ID","名称","时间","图片","性别","爱好"};
List<Object[]> dataList = new ArrayList<Object[]>();
System.out.println(dataList);
try {

//查询全部(如果想选中导出可以参考上面)
List<Dml_sd> list = login_Service.stuPoi_test();

Object[] obj = null;
for (Dml_sd gement1 : list) {

obj = new Object[rowName.length];
obj[0] = gement1.getId();
obj[1] = gement1.getName();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(gement1.getDate());
obj[2] = format;
obj[3] = gement1.getImg();
if(gement1.getImg() == null){
obj[3] = "null";
}else{
obj[3] = gement1.getImg().substring(0, gement1.getImg().lastIndexOf("."));
}
obj[4] = gement1.getSex();
if("1".equals(gement1.getSex())){
obj[4] = "男";
}else{
obj[4] = "女";
}
obj[5] = gement1.getHobby();
if(gement1.getHobby().contains("1") && gement1.getHobby().contains("2") && gement1.getHobby().contains("3")){
obj[5] = "吃饭"+ ",睡觉"+ "打豆豆";
}

if(gement1.getHobby().contains("2") && gement1.getHobby().contains("3") ){
obj[5] = "睡觉"+",打豆豆";
}

if(gement1.getHobby().contains("3") && gement1.getHobby().contains("1")){
obj[5] = "打豆豆" +",吃饭";
}
if(gement1.getHobby().contains("2") && gement1.getHobby().contains("1")){
obj[5] = "睡觉" +",吃饭";
}
if(gement1.getHobby().contains("1")){
obj[5] = "吃饭";
}
if(gement1.getHobby().contains("2")){
obj[5] = "睡觉";
}
if(gement1.getHobby().contains("3")){
obj[5] = "打豆豆";
}

System.err.println(obj);
dataList.add(obj);
}
ExportExcel2 exportExcel = new ExportExcel2(title, rowName, dataList);
exportExcel.export();
System.out.println("success");

} catch (Exception e) {
e.printStackTrace();
}

}

ExportExcel2 工具类

public class ExportExcel2{

//显示的导出表的标题
private String title;
//导出表的列名
private String[] rowName ;

private List<Object[]> dataList = new ArrayList<Object[]>();

HttpServletResponse response;

//构造方法,传入要导出的数据
public ExportExcel2(String title,String[] rowName,List<Object[]> dataList){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
this.response = response;
}
//构造方法,传入要导出的数据
public ExportExcel2(String title,String[] rowName,List<Object[]> dataList,HttpServletResponse response){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
this.response = response;
}

/*
* 导出数据
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 03版excel
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);

//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
//合并单元格 - 下标意义待查
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);




// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
//String[] rowsName = new String[] {"序号", "用户名", "姓名或企业名称", "手机号", "用户类型","充值时间","建立操作人","状态","金额(元)","审核人","审核时间","备注"};
// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
}

//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){

Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数

for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
// if(j == 0){
// cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
// cell.setCellValue(i+1);
// }else{
cell = row.createCell(j);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}
// }
cell.setCellStyle(style); //设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = 0;
if (null != currentCell.getStringCellValue() && !"".equals(currentCell.getStringCellValue())) {
length = currentCell.getStringCellValue().getBytes().length;
}

if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}

if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
/*String headStr = "attachment; filename=\"" + fileName + "\"";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream(); */
FileOutputStream out = new FileOutputStream("E:\\excel\\"+fileName+"");
System.err.println("############################################## 文件存放位置是:"+"E:\\excel\\"+fileName+"################################################");
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}

}catch(Exception e){
e.printStackTrace();
}

}

/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}

/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}
}

以上就是本人自己总结出来的不喜勿碰!欢迎大神来纠错!共同进步!需要的可以拿走不谢!!!

 

posted on 2019-01-23 11:12  UnmatchedSelf  阅读(1283)  评论(0编辑  收藏  举报

导航