package com.yktz.biz.excel;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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 com.yktz.dbConnection.JdbcConnection;
import com.yktz.util.StringUtil;
/**
* Excel数据导出
* @author Administrator
*/
public class ReadExcel {
Logger log = Logger.getLogger(this.getClass());
private Workbook wb;
private Sheet sheet;
private Row row;
public ReadExcel(String filepath) {
if (filepath == null) {
return;
}
String ext = filepath.substring(filepath.lastIndexOf("."));
try {
InputStream is = new FileInputStream(filepath);
if (".xls".equals(ext)) {
wb = new HSSFWorkbook(is);
} else if (".xlsx".equals(ext)) {
wb = new XSSFWorkbook(is);
} else {
wb = null;
}
} catch (FileNotFoundException e) {
log.error("FileNotFoundException", e);
} catch (IOException e) {
log.error("IOException", e);
}
}
/**
* 读取Excel表格表头的内容
* @param InputStream
* @return String 表头内容的数组
*/
public String[] readExcelTitle() throws Exception {
if (wb == null) {
throw new Exception("Workbook对象为空!");
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 标题总列数
int colNum = row.getPhysicalNumberOfCells();
System.out.println("colNum:" + colNum);
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
title[i] = String.valueOf((row.getCell((short) i)));
//title[i] = row.getCell(i).getCellFormula();
}
return title;
}
/**
* 读取Excel数据内容
* @param InputStream
* @return Map 包含单元格数据内容的Map对象
*/
public Map<Integer, Map<Integer, Object>> readExcelContent() throws Exception {
if (wb == null) {
throw new Exception("Workbook对象为空!");
}
Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>();
sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
Object obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.put(i, cellValue);
}
return content;
}
/**
*
* 根据Cell类型设置数据
* @param cell
* @return
*/
private Object getCellFormatValue(Cell cell) {
Object cellvalue = "";
if (cell != null) {
// 判断当前Cell的Type
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: {// 如果当前Cell的Type为NUMERIC
// 返回数值类型的值
Object inputValue = null;// 单元格值
Long longVal = Math.round(cell.getNumericCellValue());
Double doubleVal = cell.getNumericCellValue();
if(Double.parseDouble(longVal + ".0") == doubleVal){//判断是否含有小数位.0
inputValue = longVal;
}else{
inputValue = doubleVal;
}
DecimalFormat df = new DecimalFormat("#.####");//格式化为四位小数,按自己需求选择;
cellvalue=String.valueOf(df.format(inputValue));//返回String类型
break;
}
case Cell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date
if (DateUtil.isCellDateFormatted(cell)) {
// 如果是Date类型则,转化为Data格式
// data格式是带时分秒的:2013-7-10 0:00:00
// cellvalue = cell.getDateCellValue().toLocaleString();
// data格式是不带带时分秒的:2013-7-10
Date date = cell.getDateCellValue();
cellvalue = date;
} else {// 如果是纯数字
// 取得当前Cell的数值
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
// 取得当前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
default:// 默认的Cell值
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
}
/**
* Excel数据导入-客户信息数据
* @param filepath
*/
public static void readExcelToDb_customer(String filepath){
try {
ReadExcel excelReader = new ReadExcel(filepath);
// 对读取Excel表格标题测试
String[] title = excelReader.readExcelTitle();
System.out.println("获得Excel表格的标题:");
for (String s : title) {
System.err.print(s + " ");
}
System.out.println("\n====================================");
// 对读取Excel表格内容测试
Map<Integer, Map<Integer, Object>> map = excelReader.readExcelContent();
System.out.println("获得Excel表格的内容:");
/*客户记录的起始ID值*/
int index=5001;
for (int i = 1; i <= map.size(); i++) {
Map<Integer, Object> dataMap=map.get(i);
System.err.println(dataMap);
// for(int j = 1; j <= dataMap.size(); j++){
// String colValue=String.valueOf(dataMap.get(j));
// System.out.println(colValue);
// }
String customer_name=String.valueOf(dataMap.get(1)).trim();
String customer_phone=String.valueOf(dataMap.get(2)).trim();
String report_time=String.valueOf(dataMap.get(3)).trim();
if(report_time.indexOf(".")>=0){
report_time=report_time.replace(".", "-");
}
String intention=String.valueOf(dataMap.get(4)).trim();
String create_type=String.valueOf(dataMap.get(5)).trim();
String report_name=String.valueOf(dataMap.get(6)).trim();
String description=String.valueOf(dataMap.get(7)).trim();
String judge_info=String.valueOf(dataMap.get(8)).trim();
String judge_type=String.valueOf(dataMap.get(8)).trim();
String operate_name=String.valueOf(dataMap.get(9)).trim();
String familiarity_level=String.valueOf(dataMap.get(10)).trim();
String intention_level="1";
String status="1";
int creater=1;
String create_time="2014-08-16 00:00:00";
String remark="数据批量导入";
System.out.println("index11::"+index);
/*产生编码*/
String zeroStr="";
if(String.valueOf(index).length()<4){
for(int m = 0; m < 4 - String.valueOf(index).length(); m++) {
zeroStr +="0";
}
}
String codeStr=zeroStr+index;
String code="20180816"+codeStr;
/*插入客户信息*/
String insertSql1= "insert into `t_mb_customer` "
+"(`id`, `type`, `code`, `name`, `nickname`, `phone`, `gender`, `age`, `address`, `profession`, `register_flag`, `simpleName`, `status`, `create_type`, `create_userid`, `create_housesid`, `create_time`, `update_userid`, `update_time`, `remark`"
+", `intention`, `description`, `judge_type`, `judge_info`, `report_name`, `report_time`, `operate_name`, `familiarity_level`, `intention_level`)"
+" values"
+"("+index+",'1','C"+code+"','"+customer_name+"','"+customer_name+"','"+customer_phone+"','','','','','0','ly','1','"+create_type+"','44','447','"+create_time+"',NULL,NULL,'"+remark+"'"
+",'"+intention+"','"+description+"','"+judge_type+"','"+judge_info+"','"+report_name+"','"+report_time+"','"+operate_name+"','"+familiarity_level+"','"+intention_level+"')";
System.out.println("insertSql1::"+insertSql1);