java 操作Excel的方式例子

package cn.xroot.nais.constant.exceltool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author
 * @version 方法说明: 操作Excel的方式例子
 * @return
 */

public class ExcelTool {

	// 根据文件夹名称创建文件夹
	public void createLocalDir(String localPath, String dirName) throws IOException {
		File file = new File(localPath + dirName);
		file.mkdir();
	}

	// 根据文件夹名删除文件夹
	// 注意:文件夹下有文件时,无法删除该文件夹
	public void deleteLocalDirOrLocalFile(String localPath, String dirNameOrFileName) throws IOException {
		File file = new File(localPath + dirNameOrFileName);
		file.delete();
	}

	// 复制一个excel到另一个路径下,进行操作处理。
	public void copyExcelFile(String sourcePath, String destPath) throws IOException {

		File sourceFile = new File(sourcePath);

		File destFile = new File(destPath);

		InputStream input = null;
		OutputStream output = null;
		try {
			input = new FileInputStream(sourceFile);
			output = new FileOutputStream(destFile);
			byte[] buf = new byte[1024];
			int bytesRead;
			while ((bytesRead = input.read(buf)) > 0) {
				output.write(buf, 0, bytesRead);
			}
		} finally {
			input.close();
			output.close();
		}

	}

	// 读取一个excel信息
	public void loadExcelFileByFilePath_Example(String filePath, String fileName) throws IOException {

		InputStream input = new FileInputStream(filePath + fileName); // 建立输入流

		Workbook wb = null;

		// 根据文件格式(2003或者2007)来初始化
		if (fileName.endsWith("xlsx")) {
			wb = new XSSFWorkbook(input);
		} else {
			wb = new HSSFWorkbook(input);
		}

		// 获得第一个表单
		Sheet sheet = wb.getSheetAt(0);

		// 获得第一个表单的迭代器
		Iterator<Row> rows = sheet.rowIterator();

		while (rows.hasNext()) {

			// 获得行数据
			Row row = rows.next();

			// 获得行号从0开始
			System.out.println("第 " + (row.getRowNum() + 1) + " 行");

			// 获得第一行的迭代器
			Iterator<Cell> cells = row.cellIterator();

			while (cells.hasNext()) {

				Cell cell = cells.next();

				System.out.println("第 " + (cell.getColumnIndex() + 1) + " 列");

				switch (cell.getCellType()) { // 根据cell中的类型来输出数据

				case HSSFCell.CELL_TYPE_NUMERIC:
					System.out.println(cell.getNumericCellValue());
					break;
				case HSSFCell.CELL_TYPE_STRING:
					System.out.println(cell.getStringCellValue());
					break;
				case HSSFCell.CELL_TYPE_BOOLEAN:
					System.out.println(cell.getBooleanCellValue());
					break;
				case HSSFCell.CELL_TYPE_FORMULA:
					System.out.println(cell.getCellFormula());
					break;
				default:
					System.out.println("有BUG");
					break;

				}

			}

		}

		// 关闭输入流
		input.close();

	}

	// 写入excel数据 (xls)
	public void writeExcelFileByFilePath_Example(String filePath, String fileName) throws IOException {

		Workbook wb = null;

		File file = new File(filePath + fileName);

		// 创建工作文档对象
		if (!file.exists()) {
			if (fileName.endsWith("xlsx")) {
				wb = new XSSFWorkbook();
				wb.createSheet("sheet1");
			} else {
				wb = new HSSFWorkbook();
				wb.createSheet("sheet1");
			}

			// 没有excel文件,创建保存
			OutputStream outputStream = new FileOutputStream(filePath + fileName);
			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();

		} else {

			// 将excel文件以流的形式写入wb中,可以保留excel文件中的内容
			InputStream excelInput = new FileInputStream(filePath + fileName);

			if (fileName.endsWith("xlsx")) {
				wb = new XSSFWorkbook(excelInput);
			} else {
				wb = new HSSFWorkbook(excelInput);
			}

		}

		// 读取原来excel中的sheet
		Sheet sheet_1 = (Sheet) wb.getSheetAt(0);

		// 如果不需要保留,可以创建sheet 或 修改 sheet
		// Sheet sheet_1 = (Sheet) wb.createSheet("车辆事故信息");

		// 创建行
		Row row = sheet_1.createRow(0);

		// 根据行创建列
		Cell cell = row.createCell(0);

		// 行高
		row.setHeight((short) 540);
		// 行内容
		cell.setCellValue("车辆事故信息"); // 创建第一行
		// 样式对象
		CellStyle style = wb.createCellStyle();
		// 设置单元格的背景颜色为淡蓝色
		style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
		// 垂直
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		// 水平
		style.setAlignment(CellStyle.ALIGN_CENTER);
		// 指定当单元格内容显示不下时自动换行
		style.setWrapText(true);
		// 样式,居中
		cell.setCellStyle(style);

		// 字体样式
		Font font = wb.createFont();
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
		font.setFontName("宋体");
		font.setFontHeight((short) 280);
		style.setFont(font);

		// 单元格合并 注意是针对 sheet页
		// 四个参数分别是:起始行,起始列,结束行,结束列
		sheet_1.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
		// 如下代码暂时不使用
		// sheet.autoSizeColumn(5200);

		// 创建第二行 声明一个row对象即可针对整个sheet做处理 cell都是针对当前row的对象
		row = sheet_1.createRow(1);
		for (int i = 0; i < 5; i++) {
			cell = row.createCell(i);
			cell.setCellValue("第二行" + i);
			cell.setCellStyle(style); // 样式,居中
			// 注意 增加行宽也是针对sheet页
			sheet_1.setColumnWidth(i, 20 * 256);
		}
		row.setHeight((short) 540);

		// 循环写入行数据
		for (int i = 0; i < 5; i++) {
			// 创建第N行 这里+2 是因为第一行和第二行已经使用
			row = (Row) sheet_1.createRow(i + 2);
			row.setHeight((short) 500);
			// 创建第N行的多列数据
			row.createCell(0).setCellValue("列1");
			row.createCell(1).setCellValue("列2");
			row.createCell(2).setCellValue("列3");
			row.createCell(3).setCellValue("列4");
		}

		// 创建文件流
		OutputStream excelFileStream = new FileOutputStream(filePath + fileName);
		// 写入数据
		wb.write(excelFileStream);
		// 关闭文件流
		excelFileStream.close();

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值