import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.*;
public class ExcelToMysql {
public static void processData(String jdbcUrl, String username, String password, InputStream inputStream)
throws SQLException, Exception {
Connection conn = null;
PreparedStatement pstmt = null;
Workbook workbook = null;
List<Object[]> batchParams = new ArrayList<>();
try {
// Connect to database
conn = DriverManager.getConnection(jdbcUrl, username, password);
// Parse Excel file
workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
// Iterate through the rows in the sheet
for (int i = 1; i <= rowNum; i++) { // skip header row
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
// Get values from cells in the row
String column1 = getStringCellValue(row.getCell(0));
int column2 = getNumericCellValue(row.getCell(1)).intValue();
String column3 = getStringCellValue(row.getCell(2));
// Add row to batch
batchParams.add(new Object[] { column1, column2, column3 });
// Execute batch every 1000 rows
if (batchParams.size() == 1000) {
insertBatch(conn, pstmt, batchParams);
batchParams.clear();
}
}
// Insert remaining rows in batch
if (!batchParams.isEmpty()) {
insertBatch(conn, pstmt, batchParams);
}
} catch (Exception e) {
throw new Exception("Error occurred while processing Excel file and inserting data into database.");
} finally {
if (workbook != null) {
workbook.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
private static void insertBatch(Connection conn, PreparedStatement pstmt, List<Object[]> batchParams)
throws SQLException {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
for (Object[] params : batchParams) {
pstmt.setString(1, (String) params[0]);
pstmt.setInt(2, (int) params[1]);
pstmt.setString(3, (String) params[2]);
pstmt.addBatch();
}
pstmt.executeBatch();
}
private static String getStringCellValue(Cell cell) {
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue().trim();
case NUMERIC:
return String.valueOf(cell.getNumericCellValue()).trim();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue()).trim();
default:
return null;
}
}
private static Double getNumericCellValue(Cell cell) {
if (cell == null) {
return null;
}
return cell.getNumericCellValue();
}
}
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.poi.ss.usermodel.*;
public class ExcelToMysql {
public static void processData(String jdbcUrl, String username, String password, InputStream inputStream, int threadCount)
throws SQLException, Exception {
Connection conn = null;
PreparedStatement pstmt = null;
Workbook workbook = null;
try {
// Connect to database
conn = DriverManager.getConnection(jdbcUrl, username, password);
// Parse Excel file
workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum() + 1;
// Prepare insert statement
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
// Divide rows into chunks
int chunkSize = rowCount / threadCount;
int remainingRows = rowCount % threadCount;
int startRow = 1;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
int endRow = startRow + chunkSize - 1;
if (remainingRows > 0) {
endRow++;
remainingRows--;
}
int finalStartRow = startRow;
int finalEndRow = endRow;
new Thread(() -> {
try {
insertRows(conn, pstmt, sheet, finalStartRow, finalEndRow, latch);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
startRow = endRow + 1;
}
// Wait for all threads to complete
latch.await();
} catch (Exception e) {
throw new Exception("Error occurred while processing Excel file and inserting data into database.");
} finally {
if (workbook != null) {
workbook.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
private static void insertRows(Connection conn, PreparedStatement pstmt, Sheet sheet, int startRow, int endRow,
CountDownLatch latch) throws SQLException {
List<Object[]> batchParams = new ArrayList<>();
try {
// Iterate through the rows in the sheet
for (int i = startRow; i <= endRow; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
// Get values from cells in the row
String column1 = getStringCellValue(row.getCell(0));
int column2 = getNumericCellValue(row.getCell(1)).intValue();
String column3 = getStringCellValue(row.getCell(2));
// Add row to batch
batchParams.add(new Object[] { column1, column2, column3 });
// Execute batch every 1000 rows
if (batchParams.size() == 1000) {
insertBatch(conn, pstmt, batchParams);
batchParams.clear();
}
}
// Insert remaining rows in batch
if (!batchParams.isEmpty()) {
insertBatch(conn, pstmt, batchParams);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
private static void insertBatch(Connection conn, PreparedStatement pstmt, List<Object[]> batchParams)
throws SQLException {
for (Object[] params : batchParams) {
pstmt.setString(1, (String) params[0]);
pstmt.setInt(2, (int) params[1]);
pstmt.setString(3, (String) params[2]);
pstmt.addBatch();
}
pstmt.executeBatch();
}
private static String getStringCellValue(Cell cell) {
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue().trim();
case NUMERIC:
return String.valueOf(cell.getNumericCellValue()).trim();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue()).trim();
default:
return null;
}
}
private static Double getNumericCellValue(Cell cell) {
if (cell == null) {
return null;
}
return cell.getNumericCellValue();
}
}