ExcelToTxt 工具类

 

工具类

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelToTxt {

	static Logger logger = LoggerFactory.getLogger(ExcelToTxt.class);

	public static void main(String[] args) {
		String excelPath = "C:\\test\\test.xls";
		String txtPath = "C:\\test\\test.txt";
		excelToTxt(excelPath, txtPath);
	}

	public static void excelToTxt(String excelPath, String txtPath) {

		StringBuffer sb = new StringBuffer();
		Workbook workbook = readExcel(excelPath);
		Sheet sheet = workbook.getSheetAt(0);

		// 获取最大行数
		int rownum = sheet.getLastRowNum();
		// 获取最大列数
		Row row = sheet.getRow(rownum);
		int colnum = row.getLastCellNum();
		for (int i = 0; i <= rownum; i++) {
			row = sheet.getRow(i);
			if (row != null) {
				for (int j = 0; j < colnum; j++) {
					sb.append(getCellFormatValue(row.getCell(j)) + ",");
				}
			} else {
				break;
			}
			sb.append("\r\n");
		}

		WriteToFile(sb.toString(), txtPath);

	}

	// 读取excel
	private static Workbook readExcel(String filePath) {
		Workbook workbook = null;
		try {
			InputStream is = new FileInputStream(filePath);

			if (filePath.contains("xlsx")) {
				workbook = new XSSFWorkbook(is);
			} else {
				workbook = new HSSFWorkbook(is);
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return workbook;
	}

	private static Object getCellFormatValue(Cell cell) {
		Object cellValue = null;
		if (cell != null) {
			// 判断cell类型
			switch (cell.getCellType()) {
			case NUMERIC: {
				Double cellValue1 = cell.getNumericCellValue();
				cellValue = new BigDecimal(cellValue1).setScale(2, RoundingMode.HALF_UP);
				break;
			}
			case STRING: {
				cellValue = cell.getStringCellValue();
				break;
			}
			default:
				cellValue = "";
			}
		} else {
			cellValue = "";
		}
		return cellValue;
	}

	/**
	 * 生成文件
	 */
	private static void WriteToFile(String str, String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		}
		BufferedWriter bw = null;
		try {
			FileOutputStream out = new FileOutputStream(filePath, true);// true,表示:文件追加内容,不重新生成,默认为false
			bw = new BufferedWriter(new OutputStreamWriter(out, "GBK"));
			bw.write(str += "\r\n");// 换行
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

 

上一篇:POI-Excel写


下一篇:Poi工具类快速生成Ecxel(升级版)