我正在创建一个 web 应用程序,它需要从用户上传 excel 文件,并且该文件中的数据将存储在数据库中。我正在使用 postgre sql 和 spring,poi api。我有一个程序,它从 xls 和 xlsx 中提取数据并将其显示在 myeclipse 控制台上,但是我应该怎么做才能将该数据存储到数据库中。
public class ReadExcelData {
public static void main(String args[])
{
ReadExcelData read = new ReadExcelData();
try
{
System.out.println("**********Reading XLS File**************");
//reading xls file
read.readXlsFile();
System.out.println("");
System.out.println("**********Reading XLSX File**************");
//Reading xlsx file
read.readXlsxFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* This method will read the Excel file with .xls format (before MS Excel 2003 Ver.)
* @throws IOException
*/
private void readXlsFile() throws IOException
{
InputStream file = new FileInputStream("\\manage_user_info.xls");
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Getting sheet number 1
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
//Creating the Row Iterator Object
Iterator<?> rows = sheet.rowIterator();
//Iterating over the Rows of a Sheet
while (rows.hasNext())
{
row=(HSSFRow) rows.next();
Iterator<?> cells = row.cellIterator();
//Iterating over the Columns of a Row
while (cells.hasNext())
{
cell=(HSSFCell) cells.next();
//For string type data
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
//for Numeric data
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
}
}
}
/**
* This method will read the Excel file with .xlsx format
* @throws IOException
*/
private void readXlsxFile() throws IOException
{
InputStream xlsxFile = new FileInputStream("C:\\Users\\Ashwani\\Desktop\\manage_user_info.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(xlsxFile);
//Getting sheet number 1
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
//Creating the Row Iterator Object
Iterator rows = sheet.rowIterator();
//Iterating over the Rows of a Sheet
while (rows.hasNext())
{
row=( XSSFRow) rows.next();
Iterator cells = row.cellIterator();
//Iterating over the Columns of a Row
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print("--string-- ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print("--number--");
}
}System.out.println();
}
}
}