zoukankan      html  css  js  c++  java
  • java_poi



    import
    java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.junit.Test; public class poi_write { @Test public void testWrite() { final String [] str = {"id", "姓名", "性别"}; //创建Excel工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); //创建Excel工作表 HSSFSheet sheet = workbook.createSheet(); //创建第一行 HSSFRow row = sheet.createRow(0); //定义单元格 HSSFCell cell = null; //添加表头,为第一行填充内容 for (int i = 0; i < str.length; i++) { cell = row.createCell(i); cell.setCellValue(str[i]); } //追加数据,创建十行,为每行添加数据,每行三个单元格,下表依次0,1,2 for (int i = 1; i <= 10; i++) { HSSFRow rows = sheet.createRow(i); HSSFCell cell_id = rows.createCell(0); cell_id.setCellValue(i+""); HSSFCell cell_name = rows.createCell(1); cell_name.setCellValue("name:"+i); HSSFCell cell_sex = rows.createCell(2); cell_sex.setCellValue("男"); } //文件保存路径 File file = new File("E:/tmp/poi_text.xls"); try{ if(!file.exists()){ file.createNewFile(); } FileOutputStream fileOut = new FileOutputStream(file);//创建一个文件输出流对象 workbook.write(fileOut); fileOut.close();//关闭输出流对象 }catch (Exception e) { e.printStackTrace(); } System.out.println("Excel文件已生成"); } @Test public void testRead() { final File file = new File("E:/tmp/poi_text.xls"); if(file.exists()){ try { //生成workbook HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file)); // workbook.getSheet("Sheet0");//获得指定的工作表 // HSSFSheet sheet = workbook.getSheet("Sheet0"); //workbook.getSheetAt(0);//默认获得第一个工作表 HSSFSheet sheet = workbook.getSheetAt(0); int firstRowNum = 0; //获得当前sheet最后一行行号 int lastRowNum = sheet.getLastRowNum(); for (int i = firstRowNum; i <= lastRowNum; i++) { HSSFRow row = sheet.getRow(i); //获得当前行最后单元格列号 int lastCellNum = row.getLastCellNum(); for (int j = 0; j < lastCellNum; j++) { HSSFCell cell = row.getCell(j); String value = cell.getStringCellValue(); System.out.print(value+" "); } System.out.println(""); } } catch (IOException e) { e.printStackTrace(); } }else{ System.out.println("读取文件不存在"); } } }

    jar包 :poi-3.8-20120326.jar

  • 相关阅读:
    【转】 Android代码混淆之混淆规则
    【转】java虚拟机机制总结
    【转】图解 HTTP协议/IIS 原理及ASP.NET运行机制浅析
    【转】Android 消息机制
    Android-eclipse-NDK&JNI
    【转】大型网站系统架构的演化
    【转】Android开发必知--WebView加载html5实现炫酷引导页面
    【转】Java虚拟机详解----GC算法和种类
    网页中缩略图的意义
    网页开关灯效果
  • 原文地址:https://www.cnblogs.com/shaozhiqi/p/4663794.html
Copyright © 2011-2022 走看看