创建Excel代码如下:
package com.bjpowernode.poi;
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 {
/** Excel 文件要存放的位置,假定在D盘下 */
public static String outputFile = "D:\\test.xls";
public static void main(String argv[]) {
try {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值
// 如要新建一名为"效益指标"的工作表,其语句为:
// HSSFSheet sheet = workbook.createSheet("效益指标");
HSSFSheet sheet = workbook.createSheet();
// 在索引0的位置创建行(最顶端的行)
HSSFRow row = sheet.createRow(0);
// 在索引0的位置创建单元格(左上端)
HSSFCell cell = row.createCell(0);
// 定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 在单元格中输入一些内容
cell.setCellValue("增加值111111");
// 新建一输出文件流
FileOutputStream fOut = new FileOutputStream(outputFile);
// 把相应的Excel 工作簿存盘
workbook.write(fOut);
fOut.flush();
// 操作结束,关闭文件
fOut.close();
System.out.println("文件生成...");
} catch (Exception e) {
System.out.println("已运行 xlCreate() : " + e);
}
}
}
读取EXCEL:
package com.bjpowernode.poi;
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 ReadXL1 {
/** Excel文件的存放位置。注意是正斜线 */
public static String fileToBeRead = "D:\\esss\\ssss\\sssexcel模板.xls";
public static void main(String argv[]) {
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
fileToBeRead));
HSSFSheet sheet = workbook.getSheetAt(0);
int i = 0;
while (true) {
HSSFRow row = sheet.getRow(i);
if (row == null) {break;}
HSSFCell cellEmpCode = row.getCell(0);
HSSFCell cellEmpName = row.getCell(1);
HSSFCell cellEmpSex = row.getCell(2);
HSSFCell cellEmpBirthday = row.getCell(3);
HSSFCell cellEmpHomeplace = row.getCell(4);
HSSFCell cellEmpOrgCode = row.getCell(5);
HSSFCell cellEmpContactTel = row.getCell(6);
HSSFCell cellEmpEmail = row.getCell(7);
HSSFCell cellEmpZjm = row.getCell(8);
System.out.print(cellEmpCode.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpName.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpSex.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpBirthday.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpHomeplace.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpOrgCode.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpContactTel.getStringCellValue());
System.out.print(",");
System.out.print(cellEmpEmail.getStringCellValue());
System.out.print(",");
System.out.println(cellEmpZjm.getStringCellValue());
i++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("已运行xlRead() : " + e);
}
}
}
335

被折叠的 条评论
为什么被折叠?



