批量導出數據和所有導出到Excel(詳細)和mybatis 中 Foreach的用法

本人這裏用的是:SSM(Spring + SpringMVC + Maven) ,話很少說直接步入正題!!!!前端

首先須要POM包:java

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

java後端代碼:數據庫

/**
* 批量導出
* @param ids   前端選中的數據
* @param response   相應
* @param request    請求
*/
@RequestMapping("exportExcelTableman")
@ResponseBody
public void exportExcelTableman(String ids, HttpServletResponse response,HttpServletRequest request){apache

    //去數據庫查詢 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();
    }
}session

service層須要分割一下,按逗號分割,由於是多個:mybatis

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

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;

}
}

以上就是本人本身總結出來的不喜勿碰!歡迎大神來糾錯!共同進步!須要的能夠拿走不謝!!!

相關文章
相關標籤/搜索