读取Excel并解析插入数据库:
Excel如下:
java代码:
package com.pcm.web.sfm.materialprice.action;
import java.io.FileInputStream;
import java.sql.Timestamp;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import com.pcm.ejb.EJBHomeFactory;
import com.pcm.sfm.kernel.MaterialPriceInfo;
import com.pcm.sfm.model.MaterialPriceInfoKey;
import com.pcm.sfm.model.MaterialPriceInfoModel;
import com.pcm.util.Constants;
public class ImportExcel {
public static void main(String[] args) {
try {
String filepath = "C:\\Price.xls";
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filepath));
HSSFWorkbook workbook = new HSSFWorkbook(fs);//读取文件
HSSFSheet sheet = workbook.getSheetAt(0);//获取第一个工作表对象(excel中的sheet的编号从0开始;0,1,2,3,4....)
for (int i = 1, j = sheet.getLastRowNum(); i <= j-3; i++) {
HSSFCell supplyCode = sheet.getRow(i).getCell((short) 0);
String SupplyCode = supplyCode.toString();
HSSFCell supplyName = sheet.getRow(i).getCell((short) 1);
String SupplyName = supplyName.toString();
// HSSFCell partsId = sheet.getRow(i).getCell((short) 2);
// String PartsId =partsId.toString();
HSSFCell partsNo = sheet.getRow(i).getCell((short) 3);
String PartsNo = partsNo.toString();
HSSFCell partsName = sheet.getRow(i).getCell((short) 4);
String PartsName = partsName.toString();
HSSFCell purchasePrice = sheet.getRow(i).getCell((short) 5);
double PurchasePrice = purchasePrice.getNumericCellValue();
// System.out.println("供应商编码:" + SupplyCode + ",供应商名称:"
// + SupplyName+",配件ID:" + PartsId +",图号:" + PartsNo +",物料描述:"
// + PartsName +",采购价:" + PurchasePrice);
MaterialPriceInfo bizImpl = null; //接口
bizImpl = (MaterialPriceInfo) EJBHomeFactory.getFactory(com.pcm.sfm.ReferenceConst.EJB_NAME).lookupHome(MaterialPriceInfo.class);
MaterialPriceInfoModel model = new MaterialPriceInfoModel();
model.setSupplyCode(SupplyCode);
model.setSupplyName(SupplyName);
//model.setPartsId(Integer.parseInt(PartsId));
model.setPartsNo(PartsNo);
model.setPartsName(PartsName);
model.setPurchasePrice(PurchasePrice);
model.setEnableFlag(Constants.ENABLE_FLAG_TRUE);
model.setCreationDate( new Timestamp(System.currentTimeMillis()).toString());
MaterialPriceInfoKey theKey = (MaterialPriceInfoKey) bizImpl.insert(model);
if(theKey!=null){
System.out.println("导入成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}