java poi读写excel



POI中可能会用到一些需要设置EXCEL单元格格式的操作小结:

先获取工作薄对象:

HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet sheet = wb.createSheet();

HSSFCellStyle setBorder = wb.createCellStyle();

一、设置背景色:

setBorder.setFillForegroundColor((short) 13);// 设置背景色
setBorder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

二、设置边框:

setBorder.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
setBorder.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
setBorder.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
setBorder.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

三、设置居中:

setBorder.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中

四、设置字体:

HSSFFont font = wb.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 16);//设置字体大小

HSSFFont font2 = wb.createFont();
font2.setFontName("仿宋_GB2312");
font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
font2.setFontHeightInPoints((short) 12);

setBorder.setFont(font);//选择需要用到的字体格式

五、设置列宽:

sheet.setColumnWidth(0, 3766); //第一个参数代表列id(从0开始),第2个参数代表宽度值

六、设置自动换行:

setBorder.setWrapText(true);//设置自动换行

七、合并单元格:

Region region1 = new Region(0, (short) 0, 0, (short) 6);

//参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号
sheet.addMergedRegion(region1);

八、加边框

  HSSFCellStyle cellStyle= wookBook.createCellStyle();
  cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  cellStyle.setBorderBottom(HSSFCellStyle.BorderBORDER_MEDIUM);
  cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
  cellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
  cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
  cellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
  cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
  cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
  cellStyle.setTopBorderColor(HSSFColor.BLACK.index);

另附:完整小例子一个

开发环境:IntelliJ IDEA 10.0.2

@ResponseBody

@RequestMapping(value = "/reportForms/joinStocktaking/exportStorage.api")

public AjaxResponse exportStorage(@RequestBody StorageModel model) throws Exception {

if (logger.isDebugEnabled())

logger.debug("tmpdir is, {}", System.getProperty(JAVA_IO_TMPDIR));

int row = 1;


HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet hssfSheet = workbook.createSheet();

HSSFCellStyle style = workbook.createCellStyle();

style.setFillBackgroundColor(HSSFCellStyle.LEAST_DOTS);

style.setFillPattern(HSSFCellStyle.LEAST_DOTS);


//设置Excel中的边框(表头的边框)

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);

style.setBottomBorderColor(HSSFColor.BLACK.index);

style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

style.setLeftBorderColor(HSSFColor.BLACK.index);

style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);

style.setRightBorderColor(HSSFColor.BLACK.index);

style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);

style.setTopBorderColor(HSSFColor.BLACK.index);


//设置字体

HSSFFont font = workbook.createFont();

font.setFontHeightInPoints((short) 14); // 字体高度

font.setFontName(" 黑体 "); // 字体


style.setFont(font);

HSSFRow firstRow = hssfSheet.createRow((short) 0);

HSSFCell firstCell = firstRow.createCell(0);

firstRow.setHeight((short) 400);

//设置Excel中的背景

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

firstCell.setCellValue(new HSSFRichTextString("库房"));

firstCell.setCellStyle(style);


HSSFCell secondCell = firstRow.createCell(1);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

secondCell.setCellValue(new HSSFRichTextString("库区"));

secondCell.setCellStyle(style);


HSSFCell threeCell = firstRow.createCell(2);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

threeCell.setCellValue(new HSSFRichTextString("物料编号"));

threeCell.setCellStyle(style);


HSSFCell fourCell = firstRow.createCell(3);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

fourCell.setCellValue(new HSSFRichTextString("物料名称"));

fourCell.setCellStyle(style);


HSSFCell fiveCell = firstRow.createCell(4);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

fiveCell.setCellValue(new HSSFRichTextString("在库数量"));

fiveCell.setCellStyle(style);


HSSFCell sixCell = firstRow.createCell(5);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

sixCell.setCellValue(new HSSFRichTextString("锁定数量"));

sixCell.setCellStyle(style);


//设置列宽

hssfSheet.setColumnWidth(0, 7000);

hssfSheet.setColumnWidth(1, 8000);

hssfSheet.setColumnWidth(2, 4000);

hssfSheet.setColumnWidth(3, 6000);

hssfSheet.setColumnWidth(4, 4000);

hssfSheet.setColumnWidth(5, 4000);



List<?> list = joinStocktackingService.findjoinStorageByTerm(model.getWareHouse(), model.getStockArea(), model.getMaterialCode(), model.getMaterialName());

for (Object object : list) {

Object[] objects = (Object[]) object;

Storage storage = (Storage) objects[0];

Warehouse warehouse = (Warehouse) objects[1];

StockArea stockArea = (StockArea) objects[2];

Material material = (Material) objects[3];



//设置Excel中的边框

HSSFCellStyle cellStyle = workbook.createCellStyle();

cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

cellStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);

cellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);

cellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setRightBorderColor(HSSFColor.BLACK.index);

cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setTopBorderColor(HSSFColor.BLACK.index);



HSSFRow hssfRow = hssfSheet.createRow((short) row);

HSSFCell firstHssfCell = hssfRow.createCell(0);//库房

firstHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

firstHssfCell.setCellValue(new HSSFRichTextString(warehouse.getName()));

firstHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell secondHssfCell = hssfRow.createCell(1);

secondHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

secondHssfCell.setCellValue(new HSSFRichTextString(stockArea.getName()));

secondHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell threeHssfCell = hssfRow.createCell(2);

threeHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

threeHssfCell.setCellValue(new HSSFRichTextString(material.getCode()));

threeHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell fourHssfCell = hssfRow.createCell(3);

fourHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

fourHssfCell.setCellValue(new HSSFRichTextString(material.getName()));

fourHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell fiveHssfCell = hssfRow.createCell(4);

fiveHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

fiveHssfCell.setCellValue(new HSSFRichTextString(String.valueOf(storage.getQty())));

fiveHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell sixHssfCell = hssfRow.createCell(5);

sixHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

sixHssfCell.setCellValue(new HSSFRichTextString(String.valueOf(storage.getQtyLocked())));

sixHssfCell.setCellStyle(cellStyle);//设置单元格的样式


row++;

}

String newFileName = String.format("%s.%s", "joinStocktaking-" + (new Date()).getTime(), "xls");

String uploadPath = FileUtils.contractPath(System.getProperty(JAVA_IO_TMPDIR), newFileName);

FileOutputStream fOut = new FileOutputStream(uploadPath);

workbook.write(fOut);

fOut.flush();

fOut.close();


return AjaxResponse.createSuccess(newFileName);

}

再来张最终效果图:

poi Excel 设置样式 - 賢賢 - ╉落淚的魚 — 賢┽

 



 示例1将演示
    如何利用
Jakarta POI API 创建Excel 文档。
   

 1 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 2 import org.apache.poi.hssf.usermodel.HSSFSheet;
 3 import org.apache.poi.hssf.usermodel.HSSFRow;
 4 import org.apache.poi.hssf.usermodel.HSSFCell;
 5 import java.io.FileOutputStream;
 6 public  class CreateXL  {
 7 /** Excel 文件要存放的位置,假定在D盘JTest目录下*/
 8 public static String outputFile="D:/JTest/ gongye.xls";
 9 public static void main(String argv[]){
10     try{
11      // 创建新的Excel 工作簿
12      HSSFWorkbook workbook = new HSSFWorkbook();
13      // 在Excel工作簿中建一工作表,其名为缺省值
14      // 如要新建一名为"效益指标"的工作表,其语句为:
15      // HSSFSheet sheet = workbook.createSheet("效益指标");
16      HSSFSheet sheet = workbook.createSheet();
17      // 在索引0的位置创建行(最顶端的行)
18      HSSFRow row = sheet.createRow((short)0);
19      //在索引0的位置创建单元格(左上端)
20      HSSFCell cell = row.createCell((short) 0);
21      // 定义单元格为字符串类型
22      cell.setCellType(HSSFCell.CELL_TYPE_STRING);
23      // 在单元格中输入一些内容
24      cell.setCellValue("增加值");
25      // 新建一输出文件流
26      FileOutputStream fOut = new FileOutputStream(outputFile);
27      // 把相应的Excel 工作簿存盘
28      workbook.write(fOut);
29      fOut.flush();
30      // 操作结束,关闭文件
31      fOut.close();
32      System.out.println("文件生成");
33    
34    
35     }
catch(Exception e) {
36      System.out.println("已运行 xlCreate() : " + e );
37     }

38    }

39}


读取Excel文档中的数据
  示例2将演示如何读取Excel文档中的数据。假定在DJTest目录下有一个文件名为gongye.xlsExcel文件。

  示例2程序如下:

 

 1 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 2 import org.apache.poi.hssf.usermodel.HSSFSheet;
 3 import org.apache.poi.hssf.usermodel.HSSFRow;
 4 import org.apache.poi.hssf.usermodel.HSSFCell;
 5 import java.io.FileInputStream;
 6 public  class ReadXL  {
 7 /** Excel文件的存放位置。注意是正斜线*/
 8 public static String fileToBeRead="D:/JTest/ gongye.xls";
 9 public static void main(String argv[])
10 try{
11  // 创建对Excel工作簿文件的引用
12  HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
13  // 创建对工作表的引用。
14  // 本例是按名引用(让我们假定那张表有着缺省名"Sheet1")
15  HSSFSheet sheet = workbook.getSheet("Sheet1");
16  // 也可用getSheetAt(int index)按索引引用,
17  // 在Excel文档中,第一张工作表的缺省索引是0,
18  // 其语句为:HSSFSheet sheet = workbook.getSheetAt(0);
19  // 读取左上端单元
20  HSSFRow row = sheet.getRow(0);
21  HSSFCell cell = row.getCell((short)0);
22  // 输出单元内容,cell.getStringCellValue()就是取所在单元的值
23  System.out.println("左上端单元是: " + cell.getStringCellValue()); 
24 }
catch(Exception e) {
25  System.out.println("已运行xlRead() : " + e );
26 }

27}

 设置单元格格式

  在这里,我们将只介绍一些和格式设置有关的语句,我们假定workbook就是对一个工作簿的引用。在Java中,第一步要做的就是创建和设置字体和单元格的格式,然后再应用这些格式:

    

    1、创建字体,设置其为红色、粗体:

1 HSSFFont font = workbook.createFont();
2 font.setColor(HSSFFont.COLOR_RED);
3 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

 

    2、创建格式

1 HSSFCellStyle cellStyle= workbook.createCellStyle();
2 cellStyle.setFont(font);

 
    3、应用格式 

 

1 HSSFCell cell = row.createCell(( short) 0);
2 cell.setCellStyle(cellStyle);
3 cell.setCellType(HSSFCell.CELL_TYPE_STRING);
4 cell.setCellValue("标题 ");

 

    总之,如本篇文章所演示的一样,Java程序员不必担心Excel工作表中的数据了,利用Jakarta POI API我们就可以轻易的在程序中存取Excel文档。



POI中可能会用到一些需要设置EXCEL单元格格式的操作小结:

先获取工作薄对象:

HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet sheet = wb.createSheet();

HSSFCellStyle setBorder = wb.createCellStyle();

一、设置背景色:

setBorder.setFillForegroundColor((short) 13);// 设置背景色
setBorder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

二、设置边框:

setBorder.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
setBorder.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
setBorder.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
setBorder.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

三、设置居中:

setBorder.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中

四、设置字体:

HSSFFont font = wb.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 16);//设置字体大小

HSSFFont font2 = wb.createFont();
font2.setFontName("仿宋_GB2312");
font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
font2.setFontHeightInPoints((short) 12);

setBorder.setFont(font);//选择需要用到的字体格式

五、设置列宽:

sheet.setColumnWidth(0, 3766); //第一个参数代表列id(从0开始),第2个参数代表宽度值

六、设置自动换行:

setBorder.setWrapText(true);//设置自动换行

七、合并单元格:

Region region1 = new Region(0, (short) 0, 0, (short) 6);

//参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号
sheet.addMergedRegion(region1);

八、加边框

  HSSFCellStyle cellStyle= wookBook.createCellStyle();
  cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  cellStyle.setBorderBottom(HSSFCellStyle.BorderBORDER_MEDIUM);
  cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
  cellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
  cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);
  cellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
  cellStyle.setRightBorderColor(HSSFColor.BLACK.index);
  cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
  cellStyle.setTopBorderColor(HSSFColor.BLACK.index);

另附:完整小例子一个

开发环境:IntelliJ IDEA 10.0.2

@ResponseBody

@RequestMapping(value = "/reportForms/joinStocktaking/exportStorage.api")

public AjaxResponse exportStorage(@RequestBody StorageModel model) throws Exception {

if (logger.isDebugEnabled())

logger.debug("tmpdir is, {}", System.getProperty(JAVA_IO_TMPDIR));

int row = 1;


HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet hssfSheet = workbook.createSheet();

HSSFCellStyle style = workbook.createCellStyle();

style.setFillBackgroundColor(HSSFCellStyle.LEAST_DOTS);

style.setFillPattern(HSSFCellStyle.LEAST_DOTS);


//设置Excel中的边框(表头的边框)

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);

style.setBottomBorderColor(HSSFColor.BLACK.index);

style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

style.setLeftBorderColor(HSSFColor.BLACK.index);

style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);

style.setRightBorderColor(HSSFColor.BLACK.index);

style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);

style.setTopBorderColor(HSSFColor.BLACK.index);


//设置字体

HSSFFont font = workbook.createFont();

font.setFontHeightInPoints((short) 14); // 字体高度

font.setFontName(" 黑体 "); // 字体


style.setFont(font);

HSSFRow firstRow = hssfSheet.createRow((short) 0);

HSSFCell firstCell = firstRow.createCell(0);

firstRow.setHeight((short) 400);

//设置Excel中的背景

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

firstCell.setCellValue(new HSSFRichTextString("库房"));

firstCell.setCellStyle(style);


HSSFCell secondCell = firstRow.createCell(1);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

secondCell.setCellValue(new HSSFRichTextString("库区"));

secondCell.setCellStyle(style);


HSSFCell threeCell = firstRow.createCell(2);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

threeCell.setCellValue(new HSSFRichTextString("物料编号"));

threeCell.setCellStyle(style);


HSSFCell fourCell = firstRow.createCell(3);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

fourCell.setCellValue(new HSSFRichTextString("物料名称"));

fourCell.setCellStyle(style);


HSSFCell fiveCell = firstRow.createCell(4);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

fiveCell.setCellValue(new HSSFRichTextString("在库数量"));

fiveCell.setCellStyle(style);


HSSFCell sixCell = firstRow.createCell(5);

firstRow.setHeight((short) 400);

style.setFillForegroundColor(HSSFColor.GREEN.index);

style.setFillBackgroundColor(HSSFColor.GREEN.index);

sixCell.setCellValue(new HSSFRichTextString("锁定数量"));

sixCell.setCellStyle(style);


//设置列宽

hssfSheet.setColumnWidth(0, 7000);

hssfSheet.setColumnWidth(1, 8000);

hssfSheet.setColumnWidth(2, 4000);

hssfSheet.setColumnWidth(3, 6000);

hssfSheet.setColumnWidth(4, 4000);

hssfSheet.setColumnWidth(5, 4000);



List<?> list = joinStocktackingService.findjoinStorageByTerm(model.getWareHouse(), model.getStockArea(), model.getMaterialCode(), model.getMaterialName());

for (Object object : list) {

Object[] objects = (Object[]) object;

Storage storage = (Storage) objects[0];

Warehouse warehouse = (Warehouse) objects[1];

StockArea stockArea = (StockArea) objects[2];

Material material = (Material) objects[3];



//设置Excel中的边框

HSSFCellStyle cellStyle = workbook.createCellStyle();

cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

cellStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);

cellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);

cellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setRightBorderColor(HSSFColor.BLACK.index);

cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);

cellStyle.setTopBorderColor(HSSFColor.BLACK.index);



HSSFRow hssfRow = hssfSheet.createRow((short) row);

HSSFCell firstHssfCell = hssfRow.createCell(0);//库房

firstHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

firstHssfCell.setCellValue(new HSSFRichTextString(warehouse.getName()));

firstHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell secondHssfCell = hssfRow.createCell(1);

secondHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

secondHssfCell.setCellValue(new HSSFRichTextString(stockArea.getName()));

secondHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell threeHssfCell = hssfRow.createCell(2);

threeHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

threeHssfCell.setCellValue(new HSSFRichTextString(material.getCode()));

threeHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell fourHssfCell = hssfRow.createCell(3);

fourHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

fourHssfCell.setCellValue(new HSSFRichTextString(material.getName()));

fourHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell fiveHssfCell = hssfRow.createCell(4);

fiveHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

fiveHssfCell.setCellValue(new HSSFRichTextString(String.valueOf(storage.getQty())));

fiveHssfCell.setCellStyle(cellStyle);//设置单元格的样式


HSSFCell sixHssfCell = hssfRow.createCell(5);

sixHssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);

sixHssfCell.setCellValue(new HSSFRichTextString(String.valueOf(storage.getQtyLocked())));

sixHssfCell.setCellStyle(cellStyle);//设置单元格的样式


row++;

}

String newFileName = String.format("%s.%s", "joinStocktaking-" + (new Date()).getTime(), "xls");

String uploadPath = FileUtils.contractPath(System.getProperty(JAVA_IO_TMPDIR), newFileName);

FileOutputStream fOut = new FileOutputStream(uploadPath);

workbook.write(fOut);

fOut.flush();

fOut.close();


return AjaxResponse.createSuccess(newFileName);

}

再来张最终效果图:

poi Excel 设置样式 - 賢賢 - ╉落淚的魚 — 賢┽

 



 示例1将演示
    如何利用
Jakarta POI API 创建Excel 文档。
   

 1 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 2 import org.apache.poi.hssf.usermodel.HSSFSheet;
 3 import org.apache.poi.hssf.usermodel.HSSFRow;
 4 import org.apache.poi.hssf.usermodel.HSSFCell;
 5 import java.io.FileOutputStream;
 6 public  class CreateXL  {
 7 /** Excel 文件要存放的位置,假定在D盘JTest目录下*/
 8 public static String outputFile="D:/JTest/ gongye.xls";
 9 public static void main(String argv[]){
10     try{
11      // 创建新的Excel 工作簿
12      HSSFWorkbook workbook = new HSSFWorkbook();
13      // 在Excel工作簿中建一工作表,其名为缺省值
14      // 如要新建一名为"效益指标"的工作表,其语句为:
15      // HSSFSheet sheet = workbook.createSheet("效益指标");
16      HSSFSheet sheet = workbook.createSheet();
17      // 在索引0的位置创建行(最顶端的行)
18      HSSFRow row = sheet.createRow((short)0);
19      //在索引0的位置创建单元格(左上端)
20      HSSFCell cell = row.createCell((short) 0);
21      // 定义单元格为字符串类型
22      cell.setCellType(HSSFCell.CELL_TYPE_STRING);
23      // 在单元格中输入一些内容
24      cell.setCellValue("增加值");
25      // 新建一输出文件流
26      FileOutputStream fOut = new FileOutputStream(outputFile);
27      // 把相应的Excel 工作簿存盘
28      workbook.write(fOut);
29      fOut.flush();
30      // 操作结束,关闭文件
31      fOut.close();
32      System.out.println("文件生成");
33    
34    
35     }
catch(Exception e) {
36      System.out.println("已运行 xlCreate() : " + e );
37     }

38    }

39}


读取Excel文档中的数据
  示例2将演示如何读取Excel文档中的数据。假定在DJTest目录下有一个文件名为gongye.xlsExcel文件。

  示例2程序如下:

 

 1 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 2 import org.apache.poi.hssf.usermodel.HSSFSheet;
 3 import org.apache.poi.hssf.usermodel.HSSFRow;
 4 import org.apache.poi.hssf.usermodel.HSSFCell;
 5 import java.io.FileInputStream;
 6 public  class ReadXL  {
 7 /** Excel文件的存放位置。注意是正斜线*/
 8 public static String fileToBeRead="D:/JTest/ gongye.xls";
 9 public static void main(String argv[])
10 try{
11  // 创建对Excel工作簿文件的引用
12  HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
13  // 创建对工作表的引用。
14  // 本例是按名引用(让我们假定那张表有着缺省名"Sheet1")
15  HSSFSheet sheet = workbook.getSheet("Sheet1");
16  // 也可用getSheetAt(int index)按索引引用,
17  // 在Excel文档中,第一张工作表的缺省索引是0,
18  // 其语句为:HSSFSheet sheet = workbook.getSheetAt(0);
19  // 读取左上端单元
20  HSSFRow row = sheet.getRow(0);
21  HSSFCell cell = row.getCell((short)0);
22  // 输出单元内容,cell.getStringCellValue()就是取所在单元的值
23  System.out.println("左上端单元是: " + cell.getStringCellValue()); 
24 }
catch(Exception e) {
25  System.out.println("已运行xlRead() : " + e );
26 }

27}

 设置单元格格式

  在这里,我们将只介绍一些和格式设置有关的语句,我们假定workbook就是对一个工作簿的引用。在Java中,第一步要做的就是创建和设置字体和单元格的格式,然后再应用这些格式:

    

    1、创建字体,设置其为红色、粗体:

1 HSSFFont font = workbook.createFont();
2 font.setColor(HSSFFont.COLOR_RED);
3 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

 

    2、创建格式

1 HSSFCellStyle cellStyle= workbook.createCellStyle();
2 cellStyle.setFont(font);

 
    3、应用格式 

 

1 HSSFCell cell = row.createCell(( short) 0);
2 cell.setCellStyle(cellStyle);
3 cell.setCellType(HSSFCell.CELL_TYPE_STRING);
4 cell.setCellValue("标题 ");

 

    总之,如本篇文章所演示的一样,Java程序员不必担心Excel工作表中的数据了,利用Jakarta POI API我们就可以轻易的在程序中存取Excel文档。


### 回答1: Java POI是一种用于读取和写入Microsoft Office格式文件的Java API。它可以读取和写入Excel、Word和PowerPoint文件。使用Java POI读取Excel文件可以使用HSSF和XSSF API。HSSF用于读取Excel 97-2003文件格式(.xls),而XSSF用于读取Excel 2007及更高版本的文件格式(.xlsx)。使用POI读取Excel文件需要创建工作簿(Workbook)、工作表(Sheet)和行(Row)对象,然后使用这些对象来读取单元格(Cell)的值。读取Excel文件时,可以使用POI提供的各种方法来获取单元格的值、格式、样式等信息。使用Java POI读取Excel文件的工具类可以简化读取Excel文件的过程,提高代码的可读性和可维护性。 ### 回答2: Java POI 是一个 Java API,可以帮助我们读取、写入和操作 Microsoft Office 格式的文档,包括 Excel、Word 和 PowerPoint 等。在 Java 开发中,使用 Java POI 可以轻松地读取 Excel 文件。 读取 Excel 文件,需要使用工具类。下面我们来看一下如何使用 Java POI 读取 Excel 工具类。 第一步:添加依赖 在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 第二步:定义工具类 在项目中定义读取 Excel 的工具类,包含以下方法: ```java public static List<List<String>> readExcel(String filePath, int sheetIndex) throws IOException { FileInputStream fis = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(sheetIndex); List<List<String>> dataList = new ArrayList<>(); for (int i = 0; i <= sheet.getLastRowNum(); i++) { List<String> rowList = new ArrayList<>(); Row row = sheet.getRow(i); if (row == null) { continue; } for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); if (cell == null) { rowList.add(""); } else { rowList.add(cell.toString()); } } dataList.add(rowList); } fis.close(); return dataList; } ``` 该方法接受 Excel 文件路径和工作表的索引,返回一个二维 List,存储了读取的 Excel 数据。 第三步:调用工具类 在需要读取 Excel 的地方,调用工具类的 readExcel 方法即可。 例如: ```java List<List<String>> dataList = ExcelUtils.readExcel("example.xlsx", 0); for (List<String> rowList : dataList) { for (String cellValue : rowList) { System.out.print(cellValue + "\t"); } System.out.println(); } ``` 上述示例会读取 example.xlsx 文件中第一个工作表的所有数据,并输出到控制台。 总结 Java POI 是一种强大的 Java API,可以帮助我们读取、写入和操作 Microsoft Office 格式的文档。本文介绍了使用 Java POI 读取 Excel 的工具类,适用于大部分 Java 项目的开发。 ### 回答3: Java POI是一个开源JAVA API,它提供了读取、写入和操作Microsoft Office格式文件的能力。其中,读取Excel文件是它的一个重要功能。 Java POI读取Excel的工具类一般分为以下步骤: 1. 创建文件输入流和Workbook对象,根据文件名或流读取Excel文件; ``` // 创建文件输入流 InputStream inputStream = new FileInputStream(filePath); // 根据文件输入流,创建Workbook对象 Workbook workbook = WorkbookFactory.create(inputStream); ``` 2. 选择读取的Sheet表单,若不指定则默认读取第一个Sheet表单; ``` // 根据指定Sheet名称,获取Sheet对象 Sheet sheet = workbook.getSheet(sheetName); // 若未指定Sheet名称,则默认读取第一个Sheet if (sheet == null) { sheet = workbook.getSheetAt(0); } ``` 3. 遍历Sheet的每一行,并读取每一列的值; ``` // 遍历每一行 for (Row row : sheet) { // 遍历每一列 for (Cell cell : row) { // 获取单元格的值 String cellValue = ""; switch (cell.getCellType()) { case STRING: cellValue = cell.getStringCellValue(); break; case NUMERIC: cellValue = String.valueOf(cell.getNumericCellValue()); break; case BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: cellValue = cell.getCellFormula(); break; default: cellValue = ""; break; } // 打印单元格的值 System.out.println(cellValue); } } ``` 4. 关闭文件输入流和Workbook对象; ``` // 关闭输入流 if (inputStream != null) { inputStream.close(); } // 关闭Workbook if (workbook != null) { workbook.close(); } ``` 以上是Java POI读取Excel的基本操作,读取的数据可以进一步进行处理和操作,比如存储到数据库、输出到文件等。同时,Java POI也支持读取其他类型的Microsoft Office格式文件,如Word和PowerPoint等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值