poi操作Excel的一些方法

来源:互联网 发布:维控触摸屏编程教程 编辑:程序博客网 时间:2024/05/18 00:04

1.修改或插入Excel的一些方法(针对xls的

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Calendar;import java.util.Date;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFPalette;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.IndexedColors;import org.apache.poi.ss.usermodel.RichTextString;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.util.CellRangeAddress;import com.mgsd.mfyg.myconst.CodeConst;public class ExcellUtill {    private String srcXlsPath = "";// // excel模板路径      private String desXlsPath = "";      private String sheetName = "";      POIFSFileSystem fs = null;      HSSFWorkbook wb = null;      HSSFSheet sheet = null;              /**      * 第一步、设置excel模板路径      * @param srcXlsPath      */      public void setSrcPath(String srcXlsPath) {          this.srcXlsPath = srcXlsPath;      }        /**      * 第二步、设置要生成excel文件路径      * @param desXlsPath      */      public void setDesPath(String desXlsPath) {          this.desXlsPath = desXlsPath;      }        /**      * 第三步、设置模板中哪个Sheet列      * @param sheetName      */      public void setSheetName(String sheetName) {          this.sheetName = sheetName;      }        /**      * 第四步、获取所读取excel模板的对象      */      public void getSheet() {          try {              File fi = new File(srcXlsPath);              if(!fi.exists()){                  System.out.println("模板文件:"+srcXlsPath+"不存在!");                  return;              }              fs = new POIFSFileSystem(new FileInputStream(fi));              wb = new HSSFWorkbook(fs);              sheet = wb.getSheet(sheetName);          } catch (FileNotFoundException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }      }        /**      * 第五步、设置字符串类型的数据      * @param rowIndex--行值      * @param cellnum--列值      * @param value--字符串类型的数据      */      public void setCellStrValue(int rowIndex, int cellnum, String value) {          HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);          cell.setCellValue(value);      }      /**      * 第五步、设置字符串类型的数据      * @param rowIndex--行值      * @param cellnum--列值      * @param value--字符串类型的数据      */      public void insertRow(String[] value,int num) {          //插入上一行表示    /*sheet.shiftRows(sheet.getLastRowNum(),sheet.getLastRowNum(), 1,true,false);    Row row = sheet.createRow(sheet.getLastRowNum()-1);     int rowNum=sheet.getLastRowNum()-1;*/        Row row = sheet.createRow(sheet.getLastRowNum()+1);     row.setHeightInPoints(num*sheet.getDefaultRowHeightInPoints());//设置行高    sheet.setColumnWidth(6, 256*30); //设置某一列的列宽    int rowNum=row.getRowNum();        //设置单元格样式    CellStyle style=wb.createCellStyle();style.setWrapText(true);//设置可以换行//设置单元格字体HSSFFont font =wb.createFont();font.setFontHeightInPoints((short) 10);// 设置字体大小style.setFont(font);//设置单元格边框   边框颜色通过数字进行指定short index = IndexedColors.BLACK.getIndex();style.setBorderTop(CellStyle.BORDER_THIN);style.setTopBorderColor(index);//上边框颜色style.setBorderBottom(CellStyle.BORDER_THIN);style.setBottomBorderColor(index);//下边框颜色style.setBorderLeft(CellStyle.BORDER_THIN);style.setLeftBorderColor(index);//左边框颜色style.setBorderRight(CellStyle.BORDER_THIN);style.setLeftBorderColor(index);//右边框颜色//填充单元格背景颜色/* String color="#000000"; int r=Integer.parseInt((color.substring(0,2)),16); int g=Integer.parseInt((color.substring(2,4)),16); int b=Integer.parseInt((color.substring(4,6)),16); HSSFPalette palette=wb.getCustomPalette(); palette.setColorAtIndex((short)11, (byte)r,(byte)g, (byte)b); style.setFillForegroundColor((short)11); style.setFillPattern(CellStyle.SOLID_FOREGROUND);//填充方式*/    for(int i=0;i<value.length;i++){    Cell cell=row.createCell(i);    cell.setCellStyle(style);    cell.setCellValue(value[i]);    }    }         /**      * 合并某行单元格     */     public void mergeCell(int rowNum,int startCell,int endCell,String value){        sheet.addMergedRegion(new CellRangeAddress(sheet.getLastRowNum(),//起始行sheet.getLastRowNum(),//结束行 startCell,//起始列 endCell//结束列));HSSFCell cell = sheet.getRow(sheet.getLastRowNum()).getCell(startCell); cell.setCellValue(value);    }        /**      * 合并行     */ public void mergeRow(int startRow,int endRow,int startCell,int endCell,String value){        sheet.addMergedRegion(new CellRangeAddress(    startRow,//起始行    endRow,//结束行 startCell,//起始列 endCell//结束列));   }    /**      * 第五步、设置日期/时间类型的数据      * @param rowIndex--行值      * @param cellnum--列值      * @param value--日期/时间类型的数据      */      public void setCellDateValue(int rowIndex, int cellnum, Date value) {          HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);          cell.setCellValue(value);      }        /**      * 第五步、设置浮点类型的数据      * @param rowIndex--行值      * @param cellnum--列值      * @param value--浮点类型的数据      */      public void setCellDoubleValue(int rowIndex, int cellnum, double value) {          HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);          cell.setCellValue(value);      }        /**      * 第五步、设置Bool类型的数据      * @param rowIndex--行值      * @param cellnum--列值      * @param value--Bool类型的数据      */      public void setCellBoolValue(int rowIndex, int cellnum, boolean value) {          HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);          cell.setCellValue(value);      }        /**      * 第五步、设置日历类型的数据      * @param rowIndex--行值      * @param cellnum--列值      * @param value--日历类型的数据      */      public void setCellCalendarValue(int rowIndex, int cellnum, Calendar value) {          HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);          cell.setCellValue(value);      }        /**      * 第五步、设置富文本字符串类型的数据。可以为同一个单元格内的字符串的不同部分设置不同的字体、颜色、下划线      * @param rowIndex--行值      * @param cellnum--列值      * @param value--富文本字符串类型的数据      */      public void setCellRichTextStrValue(int rowIndex, int cellnum,              RichTextString value) {          HSSFCell cell = sheet.getRow(rowIndex).getCell(cellnum);          cell.setCellValue(value);      }        /**      * 第六步、完成导出      */      public void exportToNewFile() {          FileOutputStream out;          try {              out = new FileOutputStream(desXlsPath);              wb.write(out);              out.close();          } catch (FileNotFoundException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }      }    }}


2.通过模板导出Excel(调用上例中的一些方法)

                ExcellUtill utill=new ExcellUtill();utill.setSrcPath("E:\\1.xls");utill.setDesPath("E:\\2.xls");utill.setSheetName("sheet1");utill.getSheet();String[] s1={"1","","","3","4"};utill.insertRow(s1,2);utill.mergeRow(2,3,0,0,"");utill.setCellStrValue(2, 0,"合并");utill.exportToNewFile();

3.在网页中导出Excel(调用上例中一些方法)

               ExcellUtill utill=new ExcellUtill();//插入的一些方法HSSFWorkbook wb = utill.getWb();//处理浏览器乱码问题String fileName=temp.getProname();String agent = request.getHeader("USER-AGENT").toLowerCase();   if(agent.indexOf("msie") > 0||agent.indexOf("trident")>0){// IE                    fileName = URLEncoder.encode(fileName, "UTF-8");            fileName = fileName.replace("+", "%20");// 处理空格变“+”的问题     }else{// 其他浏览器   fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");     } response.setHeader("Content-Disposition","attachment;filename="+ fileName+".xls");response.setContentType("application/ynd.ms-excel;charset=UTF-8");out = response.getOutputStream();wb.write(out);out.flush();





0 0
原创粉丝点击