POI实现文件读取与写出Excel文档
入门demo:
package studyPOI; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; public class MSExcel { public static void main(String[] args) throws FileNotFoundException, IOException { new MSExcel().helloExcel(); } private void helloExcel() throws FileNotFoundException,IOException { String fileStr = "F:/hello.xls"; File file = new File(fileStr); FileInputStream fim = new FileInputStream(file); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fim); HSSFSheet sheet = hssfWorkbook.getSheetAt(0); for (Row row : sheet) { System.out.println("row"+row); for (Cell cell : row) { if (cell.getCellType() == CellType.NUMERIC) { double value = cell.getNumericCellValue(); System.out.println("number:"+value); }else if (cell.getCellType() == CellType.STRING) { String value = cell.getStringCellValue(); System.out.println("value:"+value); } CellStyle cellStyle = hssfWorkbook.createCellStyle(); System.out.println("IndexedColors.BLUE.getIndex()"+IndexedColors.BLUE.getIndex()); cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%")); cell.setCellValue(8.88); cell.setCellStyle(cellStyle); } } FileOutputStream outputStream = new FileOutputStream(file); hssfWorkbook.write(outputStream); hssfWorkbook.close(); fim.close(); } }