简单的小工具,使用poi.jar,帮小白朋友处理excel
package com.excel;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.DecimalFormat;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class SimpleExcel {
public void importExcel(String filePath) throws InvalidFormatException, IOException {
File fi = new File(filePath);
InputStream fis = new FileInputStream(fi);
//poi.jar
Workbook workbook = WorkbookFactory.create(fis);
int n = 0;
Sheet sheet = workbook.getSheetAt(n);//第n页表格
int rows = sheet.getLastRowNum();
Row row;
for (int i = 0; i < rows; i++) {
row = sheet.getRow(i);
System.out.println(this.getRowValue(row,4).trim());//row和column index从0开始
}
}
// XSSFCell可以达到相同的效果
private String getRowValue(Row row, int columnNum) {
Cell cell = row.getCell(columnNum);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC: // 数字
cellValue = new DecimalFormat("0").format(cell.getNumericCellValue());
break;
case XSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case XSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case XSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case XSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
return cellValue;
}
public void exportTxt(String filePath, String contentStr) throws IOException {
File file = new File(filePath);
Writer writer = new FileWriter(file);
Writer bufWriter = new BufferedWriter(writer);
bufWriter.write(contentStr);
bufWriter.close();
}
public static void main(String[] args) {
SimpleExcel se = new SimpleExcel();
// try {
// String filePath = "D:/21.xlsx";
// se.importExcel(filePath);
// } catch (InvalidFormatException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
try {
se.exportTxt("D:/tjc.txt", "tjc1\r\ntjc2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}