Excel 导数据到数据库

徘徊边缘 提交于 2021-01-19 10:11:25

在此输入图片描述 图片为excel数据

package com.msi.excel;

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; 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.DateUtil; 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 com.msi.dao.DBConnection; import com.msi.dao.DiaryDao; import com.msi.model.Diary; import com.msi.model.PageBean;

/*

  • Excel 数据转换成 JavaBean 主要是将数据整合下如何的格式,然后遍历,顺序给JavaBean赋值
  • [A, B, C, D, E] */

public class ReadExcel {

// 將List写入Excel ,然後通过在网页上使用,便于导出excel
public static String TransXLSFileLot(List<Diary> list, String path) {
	String result = "";
	String header[] = { "diaryId", "title", "content", "typeId",
			"releaseDate" };
	Workbook workbook = new HSSFWorkbook();

	CellStyle style1 = workbook.createCellStyle();
	style1.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
	style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
	style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
	style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	// 生成一个字体
	Font font2 = workbook.createFont();
	font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
	// 把字体应用到当前的样式
	style1.setFont(font2);
	Sheet sheet = workbook.createSheet("Test");
	Row rowHeader = sheet.createRow(0);
	for (int i = 0; i < header.length; i++) {
		Cell cell = rowHeader.createCell(i); // 行添加單元格
		cell.setCellStyle(style1);
		cell.setCellValue(header[i]);
	}

	for (int j = 0; j < list.size(); j++) {
		Diary diary = list.get(j);
		Row rowBody = sheet.createRow(j + 1);
		rowBody.createCell(0).setCellValue(diary.getDiaryId());
		rowBody.createCell(1).setCellValue(diary.getTitle());
		rowBody.createCell(2).setCellValue(diary.getContent());
		rowBody.createCell(3).setCellValue(diary.getTypeId());
		rowBody.createCell(4).setCellValue(
				com.msi.util.DateUtil.formatDate(diary.getReleaseDate(),
						"yyyy-MM-dd"));
	}

	OutputStream os = null;
	BufferedOutputStream bos = null;
	try {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
			System.err.print("存在就先刪除,然後在寫入。。。。");
		} else {
			file.createNewFile();
		}
		os = new FileOutputStream(file);
		bos = new BufferedOutputStream(os);
		workbook.write(bos);
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		result = e.getMessage();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		result = e.getMessage();
	} finally {
		try {
			bos.close();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	return result;
}

// 参考网址 http://www.2cto.com/kf/201108/100774.html
public static String getValue(Cell cell) {
	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
	String value = "";
	switch (cell.getCellType()) {
	case Cell.CELL_TYPE_NUMERIC: // 数值型 分为String 类型和int 型的
		if (DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则,获取该cell的date值
			value = dateformat.format(
					DateUtil.getJavaDate(cell.getNumericCellValue()))
					.toString();
		} else {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			String temp = cell.getStringCellValue();
			if (temp.indexOf(".") > -1) {
				value = String.valueOf(new Double(temp)).trim();
			} else {
				value = temp.trim();
			}
		}
		break;
	case Cell.CELL_TYPE_STRING: // 字符串型
		// value = cell.getRichStringCellValue().toString();
		value = cell.getStringCellValue().trim();
		break;
	case Cell.CELL_TYPE_BOOLEAN:// 布尔
		value = " " + cell.getBooleanCellValue();
		break;
	case Cell.CELL_TYPE_FORMULA:// 公式型
		// 读公式计算值
		value = String.valueOf(cell.getNumericCellValue());
		if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
			value = cell.getRichStringCellValue().toString();
		}
		break;
	/* 此行表示该单元格值为空 */
	case Cell.CELL_TYPE_BLANK: // 空值
		value = "";
		break;
	case Cell.CELL_TYPE_ERROR: // 故障
		value = "";
		break;
	default:
		value = cell.getStringCellValue().trim();
		break;
	}
	return value;
}

// 读取Excel的表头
public static String[] getExcelHeader(String fileName) {
	InputStream is = null;
	BufferedInputStream bis = null;
	String[] title = null;
	try {
		is = new FileInputStream(new File(fileName));
		bis = new BufferedInputStream(is);
		Workbook workbook = new HSSFWorkbook(bis);
		Sheet sheet = workbook.getSheet("Test");
		Row row = sheet.getRow((int) 0);
		int colNum = row.getPhysicalNumberOfCells(); // 标题总列数
		title = new String[colNum];
		for (int i = 0; i < colNum; i++) {
			title[i] = getValue(row.getCell(i));
		}
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		try {
			bis.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	return title;
}

// 將Excel数据导入List中,此时的
public static List<List<String>> getExcel(String fileName) {
	List<List<String>> list = new ArrayList<List<String>>();
	try {
		FileInputStream fis = new FileInputStream(new File(fileName));
		Workbook wb = new HSSFWorkbook(fis); // 03,xls
		// XSSFWorkbook wb=new XSSFWorkbook(fis); //07,xlsx
		// HSSFWorkbook wb=new HSSFWorkbook(fis); //03,xls
		int sheetNum = wb.getNumberOfSheets();
		for (int i = 0; i < sheetNum; i++) { // 遍历工作簿
			Sheet sheet = null;
			sheet = wb.getSheetAt(i); // 03,xls
			// XSSFSheet sheet = wb.getSheetAt(i); //07,xlsx
			// HSSFSheet sheet = wb.getSheetAt(i); //03,xls
			int rowNum = sheet.getPhysicalNumberOfRows(); // .getLastRowNum();
			for (int j = 0; j < rowNum; j++) { // 在這裡修改,将j<= 改成了j< ;
				List<String> vecRow = new ArrayList<String>();
				Row row = sheet.getRow(j);
				// XSSFRow rRow = sheet.getRow(j); //07,xlsx
				// HSSFRow rRow = sheet.getRow(j); //03,xls
				int cellNum = row.getLastCellNum(); // 表示行的列數
				for (int k = 0; k < cellNum; k++) { // k表示递增 的列数
					vecRow.add(row.getCell(k).toString());
				}
				list.add(vecRow);
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return list;
}

// excel转化成List是主要是先转成List<String> ,然后将其拆分,然后归属到JavaBean中
public static List<Diary> getTranListFromExcel() throws Exception {

	List<List<String>> listA = getExcel("C:\\asdfg1.xls");

	List<Diary> listC = new ArrayList<Diary>();
	// 从1开始时为了将表头去掉
	for (int i = 1; i < listA.size(); i++) {
		List<String> listB = listA.get(i);
		Diary diary = new Diary();
		if (listB.get(0).indexOf(".") > -1) {
			int index = listB.get(0).indexOf(".");
			diary.setDiaryId(Integer.parseInt(listB.get(0).substring(0,
					index)));
		} else {
			diary.setDiaryId(Integer.parseInt(listB.get(0)));
		}

		diary.setTitle(listB.get(1));
		diary.setContent(listB.get(2));

		if (listB.get(3).indexOf(".") > -1) {
			int index = listB.get(3).indexOf(".");
			diary.setTypeId(Integer.parseInt(listB.get(3).substring(0,
					index)));
		} else {
			diary.setTypeId(Integer.parseInt(listB.get(3)));
		}
		diary.setReleaseDate(com.msi.util.DateUtil.formatString(
				listB.get(4), "yyyy-MM-dd"));

		listC.add(diary);
	}

	return listC;

}

public static void main(String[] args) throws Exception {
	// TODO Auto-generated method stub

	Connection conn = DBConnection.getConnection();
	PageBean pageBean = new PageBean(1, 100);
	Diary s_diary = new Diary();
	List<Diary> list = new DiaryDao().diaryList(pageBean, s_diary);
	TransXLSFileLot(list, "C:\\asdfg1.xls");

	String[] title = getExcelHeader("C:\\asdfg1.xls");
	for (int i = 0; i < title.length; i++) {
		System.out.print(title[i] + "   ");
	}

	List<List<String>> listA = getExcel("C:\\asdfg1.xls");
	for (int i = 0; i < listA.size(); i++) {
		System.out.println(listA.get(i));
	}

	List<Diary> listC = getTranListFromExcel();

	for (int i = 0; i < listC.size(); i++) {
		Diary d = listC.get(i);
		System.out.println(i + 1 + "  " + d.getDiaryId() + " "
				+ d.getTypeId() + " " + d.getTitle() + "  "
				+ d.getReleaseDate() + "  " + d.getContent());
		System.err.println("-------------");
	}
}

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!