java poi 读写操作excel

来源:互联网 发布:问道辅助软件 编辑:程序博客网 时间:2024/05/22 11:36

首先,需要导入poi jar包

 

package com.road;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

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.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;

/*******************************************************************************
 * 把list数据写入excel文件,例如:D:\\road\\result.xls
 *
 * @author xxx Date 2017-06-09
 ******************************************************************************/

public class RoadExcel {

 public static void roadResult2Excel(List<RoadEntity> roadEntityList) {

  // 以下是把计算结果写入excel文件
  // 文件输出流
  FileOutputStream fileOutputStream = null;
  // 结果文件路径
  String resultPath = "D:\\road\\result.xls";

  try {
   fileOutputStream = new FileOutputStream(resultPath);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  // 创建一个新的excel
  HSSFWorkbook workbook = new HSSFWorkbook();

  // 创建样式Header begin
  // 创建字体样式Header
  HSSFFont headerFont = workbook.createFont();
  headerFont.setFontName("黑体");
  headerFont.setFontHeightInPoints((short) 18);
  headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  HSSFCellStyle headerStyle = workbook.createCellStyle();
  headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  headerStyle.setFont(headerFont);
  // 创建样式Header end

  // 创建样式:列名 标题 begin
  // 创建字体样式:列名 标题
  HSSFFont titleFont = workbook.createFont();
  titleFont.setFontName("黑体");
  HSSFCellStyle titleStyle = workbook.createCellStyle();
  titleStyle.setFont(titleFont);
  // 创建样式:列名 标题 end

  // 创建单元格样式begin
  HSSFCellStyle cellStyle = workbook.createCellStyle();
  // 设置水平居中
  // cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  // 内容靠左
  cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  // 上下居中
  cellStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
  // 换行
  cellStyle.setWrapText(true);
  // 创建单元格样式end

  // 创建sheet页
  HSSFSheet sheet = workbook.createSheet("xxxxxxxxxxxxxx");
  // 创建header页
  HSSFHeader header = sheet.getHeader();
  // 创建excel的行数:第1行header,第2行列名,第3行开始是数据
  //数据行数
  int dataSize = 0;
  if (roadEntityList != null) {
   dataSize = roadEntityList.size();
  }
  // +2 ,是指 数据加上表头共需要的行数
  HSSFRow[] row = new HSSFRow[dataSize + 2];
  // 设置第一行为Header
  row[0] = sheet.createRow(0);
  HSSFCell headerCell = row[0].createCell(0);
  headerCell.setCellStyle(headerStyle);
  headerCell.setCellValue(new HSSFRichTextString("xxxxxxxxxxxxxxxxxx"));
  // 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
  sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
  // 设置第二行为列名
  row[1] = sheet.createRow(1);
  HSSFCell[] titleCell = new HSSFCell[6];
  // 列的宽度
  sheet.setColumnWidth(0, 30 * 256);
  sheet.setColumnWidth(1, 30 * 256);
  sheet.setColumnWidth(2, 30 * 256);
  sheet.setColumnWidth(3, 30 * 256);
  sheet.setColumnWidth(4, 30 * 256);
  sheet.setColumnWidth(5, 30 * 256);
  titleCell[0] = row[1].createCell(0);
  titleCell[0].setCellStyle(titleStyle);
  titleCell[0].setCellValue(new HSSFRichTextString("单元起点"));
  titleCell[1] = row[1].createCell(1);
  titleCell[1].setCellStyle(titleStyle);
  titleCell[1].setCellValue(new HSSFRichTextString("单元止点"));
  titleCell[2] = row[1].createCell(2);
  titleCell[2].setCellStyle(titleStyle);
  titleCell[2].setCellValue(new HSSFRichTextString("平曲线半径(m)"));
  titleCell[3] = row[1].createCell(3);
  titleCell[3].setCellStyle(titleStyle);
  titleCell[3].setCellValue(new HSSFRichTextString("纵坡(%)"));
  titleCell[4] = row[1].createCell(4);
  titleCell[4].setCellStyle(titleStyle);
  titleCell[4].setCellValue(new HSSFRichTextString("单元长度"));
  titleCell[5] = row[1].createCell(5);
  titleCell[5].setCellStyle(titleStyle);
  titleCell[5].setCellValue(new HSSFRichTextString("单元类型"));

  // 第3行开始插入数据
  // 遍历
  // excel行数:xxx + 2
  for (int j = 0; j < roadEntityList.size(); j++) {
   RoadEntity roadEntity = roadEntityList.get(j);
   row[j + 2] = sheet.createRow(j + 2);
   HSSFCell[] dataCell = new HSSFCell[6];
   for (int i = 0; i < 6; i++) {
    dataCell[i] = row[j + 2].createCell(i);
    dataCell[i].setCellType(Cell.CELL_TYPE_STRING);
    dataCell[i].setCellStyle(cellStyle);
   }
//   //
//   dataCell[0].setCellValue(new HSSFRichTextString("K22+310"));
//   //
//   dataCell[1].setCellValue(new HSSFRichTextString("K22+650"));
//   //
//   dataCell[2].setCellValue(new HSSFRichTextString("1327"));
//   //
//   dataCell[3].setCellValue(new HSSFRichTextString("-0.50"));
//   //
//   dataCell[4].setCellValue(new HSSFRichTextString("340"));
//   //
//   dataCell[5].setCellValue(new HSSFRichTextString("L"));
   
   
   //
   dataCell[0].setCellValue(new HSSFRichTextString(roadEntity.getUnitStart()));
   //
   dataCell[1].setCellValue(new HSSFRichTextString(roadEntity.getUnitEnd()));
   //
   dataCell[2].setCellValue(new HSSFRichTextString(roadEntity.getRadius()));
   //
   dataCell[3].setCellValue(new HSSFRichTextString(roadEntity.getLongGradient()));
   //
   dataCell[4].setCellValue(new HSSFRichTextString(roadEntity.getUnitLength()));
   //
   dataCell[5].setCellValue(new HSSFRichTextString(roadEntity.getUnitType()));
  }
  try {
   workbook.write(fileOutputStream);
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    fileOutputStream.close();
    workbook.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

}

 

 

 

package com.road;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;

/*******************************************************************************
 * 读excel,如:D:\\road\\S2-4-1直曲表test.xls,得到此excel文件的内容数据,处理数据,最后把结果存入另一个excel文件
 * 经测试成功;
 * 另,此处理Excel是xls文件,若处理xlsx文件则需要引用不同的api即可,没有大的差别;
 * @author xxx Date 2017-06-09
 ******************************************************************************/

public class ReadExcel {
 public static void main(String[] args) throws IOException {
  //源excel路径
  String xlsPath = "D:\\road\\S2-4-1直曲表test.xls";
  //读excel,得到数据,把数据放入list
  List<RoadEntity> list = ReadExcel.readXls(xlsPath);
  //把上面获取的list存入另一格式的excel里
  try {
   RoadExcel.roadResult2Excel(list);
  } catch (Exception e) {
   e.printStackTrace();
  }
  //
//  RoadEntity xls = null;
//  for (int i = 0; i < list.size(); i++) {
//   xls = (RoadEntity) list.get(i);
//   System.out.println(xls.getId() + "    " + xls.getUnitStart());
//
//  }

 }

 /**
  * 读取xls文件内容
  *
  * @return List<RoadEntity>对象
  * @throws IOException
  *
  */
 private static List<RoadEntity> readXls(String xlsPath) throws IOException {
  InputStream is = new FileInputStream(xlsPath);
  HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
  RoadEntity roadEntity = null;
  List<RoadEntity> list = new ArrayList<RoadEntity>();
  // 循环工作表Sheet
  for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
   // numSheet指的是第几个sheet页
   HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
   if (hssfSheet == null) {
    continue;
   }
   
   // 开始循环行Row,注意定位自己需要的行号,此处for循环里是需要根据你的业务逻辑进行修改的
   for (int rowNum = 4; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
    if (hssfRow == null) {
     continue;
    }
    roadEntity = new RoadEntity();
    // 开始循环列Cell,注意找自己需要的列。至此,所需的行和列都有了,数据就有了
    // 012345...此处是需要读取的源excel数据
    //读到数据之后,把数据一个个的放入实体RoadEntity对象中,然后RoadEntity放入List
    //例如,单元起点
    HSSFCell unitStart = hssfRow.getCell(0);
    if (unitStart == null) {
     continue;
    }
    roadEntity.setUnitStart(getValue(unitStart));
    //例如,单元止点
    HSSFCell unitEnd = hssfRow.getCell(1);
    if (unitEnd == null) {
     continue;
    }
    roadEntity.setUnitEnd(getValue(unitEnd));
    //例如,平曲线半径(m)
    HSSFCell radius = hssfRow.getCell(2);
    if (radius == null) {
     continue;
    }
    roadEntity.setRadius(getValue(radius));
    
    /**
     * 有些数据是存放在大单元格里的,是由多个小单元格合并的成的,此类数据获取也很简单,指定其位置即可
    Workbook wb = new XSSFWorkbook(is);
       Sheet sheet = wb.getSheetAt(0);
       // 遍历合并区域
       for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
           CellRangeAddress region = sheet.getMergedRegion(i); //
           int colIndex = region.getFirstColumn();             // 合并区域首列位置
           int rowNum = region.getFirstRow();                     // 合并区域首行位置
           System.out.println("第[" + i + "]个合并区域:" +  sheet.getRow(rowNum).getCell(colIndex).getStringCellValue());
       }
      
       // 直接调用,我知道合并单元格的位置:
       System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());
      
       System.out.println(sheet.getRow(3).getCell(2).getStringCellValue());
      
       wb.close();
       is.close();
    */
    
    
    //RoadEntity放入List,在数据放入list之前,需要根据你的需求,把加减乘除之类的处理好
    list.add(roadEntity);

   }
  }
  hssfWorkbook.close();
  return list;
 }

 /**
  * 得到Excel表中的值
  * @param hssfCell
  *            :Excel中的每一个格子
  * @return Excel中每一个格子中的值
  */
 private static String getValue(HSSFCell hssfCell) {
  // if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
  // // 返回布尔类型的值
  // return String.valueOf(hssfCell.getBooleanCellValue());
  // } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
  // // 返回数值类型的值
  // return String.valueOf(hssfCell.getNumericCellValue());
  // } else {
  // // 返回数值类型的值
  // // return String.valueOf(hssfCell.getNumericCellValue());
  // // 返回字符串类型的值
  // return String.valueOf(hssfCell.getStringCellValue());
  // }

  // 返回字符串类型的值
  return String.valueOf(hssfCell.getStringCellValue());
 }
}

 

package com.road;

/*******************************************************************************
 *
 * road实体类
 *
 * @author xxxx Date 2017-06-09
 ******************************************************************************/

public class RoadEntity {
 /**
  * id
  */
 private String id;
 /**
  * 单元起点
  */
 private String unitStart;
 /**
  * 单元止点
  */
 private String unitEnd;
 /**
  * 平曲线半径(m)
  */
 private String radius;
 /**
  * 纵坡(%)
  */
 private String longGradient;
 /**
  * 单元长度
  */
 private String unitLength;
 /**
  * 单元类型
  */
 private String unitType;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getUnitStart() {
  return unitStart;
 }

 public void setUnitStart(String unitStart) {
  this.unitStart = unitStart;
 }

 public String getUnitEnd() {
  return unitEnd;
 }

 public void setUnitEnd(String unitEnd) {
  this.unitEnd = unitEnd;
 }

 public String getRadius() {
  return radius;
 }

 public void setRadius(String radius) {
  this.radius = radius;
 }

 public String getLongGradient() {
  return longGradient;
 }

 public void setLongGradient(String longGradient) {
  this.longGradient = longGradient;
 }

 public String getUnitLength() {
  return unitLength;
 }

 public void setUnitLength(String unitLength) {
  this.unitLength = unitLength;
 }

 public String getUnitType() {
  return unitType;
 }

 public void setUnitType(String unitType) {
  this.unitType = unitType;
 }

}

 

 

 

 

 

 

 

 

原创粉丝点击