/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ithings.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author mlu
*/
public class ExcelToolUtil {
public static void main(String[] args) {
try {
readExcel();
writeExcel();
} catch (IOException ex) {
Logger.getLogger(ExcelToolUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 读取Excel
*/
public static void readExcel() throws IOException{
//要读取的Excel文件
InputStream in = new FileInputStream("d://1.xls");
//excel的文档对象 HSSFWorkbook用于2007以前的版本 XSSFWorkbook用于2007以后的版本
Workbook workbook = null;
try {
workbook = new HSSFWorkbook(in);
} catch (Exception e) {
workbook = new XSSFWorkbook(in);
}
//excel的表单Sheet
Sheet sheet = workbook.getSheetAt(0);
//总行数
int maxRow = sheet.getLastRowNum();
for(int i = 0; i < maxRow; i++){
Row row = sheet.getRow(i);
System.out.println(row.getCell(0));
}
in.close();
}
/**
* 新建并写Excel
*/
public static void writeExcel() throws IOException{
//excel的文档对象 HSSFWorkbook用于2007以前的版本 XSSFWorkbook用于2007以后的版本
Workbook workbook = null;
try {
workbook = new HSSFWorkbook();
} catch (Exception e) {
workbook = new XSSFWorkbook();
}
// 设置样式
CellStyle cellStyle =workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//excel的表单Sheet
Sheet sheet = workbook.createSheet("sheet_new");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue("aa");
//保存至文件
OutputStream out = new FileOutputStream("2.xls");
workbook.write(out);
out.close();
}
}