java读写excel

Share

首先,到 http://jakarta.apache.org/poi/ 下在 jakarta poi。

读excel:


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
public class ReadXL {
 //
 public static String fileToBeRead=”yourfile_dir”;
 public static void main(String argv[]){
 try{
  // 创建对Excel工作簿文件的引用
  HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
  HSSFSheet sheet = workbook.getSheet(“Sheet”);
  HSSFRow row = sheet.getRow(0);
  HSSFCell cell = row.getCell((short)0);
  System.out.println(“left_upon”+ cell.getStringCellValue());
 }catch(Exception e) {
  ………………….|
 }
}
}

写excel:

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileOutputStream;
public class CreateXL {

 //
 public static String outputFile=”yourfile_dir”;

 public static void main(String argv[]){

 try{

  // 创建新的Excel
  HSSFWorkbook workbook = new HSSFWorkbook();

  HSSFSheet sheet = workbook.createSheet();
  HSSFRow row = sheet.createRow((short)0);

  //在索引0的位置创建单元格
  HSSFCell cell = row.createCell((short) 0);
  cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  cell.setCellValue(“增加值”);
  FileOutputStream fOut = new FileOutputStream(outputFile);
  workbook.write(fOut);
  fOut.flush();
  // 操作结束,关闭文件
  fOut.close();
  System.out.println(“execute success…”);

 }catch(Exception e) {
  ……………….
 }
}
}

仅供参考!