В соответствии с вашим требованием я изменил код с Apache POI на Java Excel API для извлечения и хранения данных из Excel.
Попробуйте приведенный ниже код и дайте мне знать, если у вас возникли какие-либо проблемы...
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import jxl.Cell;
import jxl.CellType;
import jxl.CellView;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class OneMore {
private WritableCellFormat timesBoldUnderline;
private WritableCellFormat times;
private WritableWorkbook workbook;
private WritableSheet excelSheet;
private String inputFile;
private List<String> empIDs, invoiceDetails;
public void setOutputFile(String inputFile) {
this.inputFile = inputFile;
}
public void write(int SheetNumber) throws Exception {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Required", SheetNumber);
excelSheet = workbook.getSheet(SheetNumber);
createLabel(excelSheet);
}
private void createLabel(WritableSheet sheet) throws Exception {
// Lets create a times font
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
times.setWrap(true);
// create create a bold font with unterlines
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
cv.setFormat(timesBoldUnderline);
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "Invoice Details");
addCaption(sheet, 1, 0, "Emp ID");
}
private void retrieveDataFromDBAndStoreItInExcel(WritableSheet sheet) throws Exception {
// Handling data base part
Connection con = null;
Class.forName("driver name").newInstance();
con = DriverManager.getConnection("URL", "UN", "PWD");
System.out.println("Connection Created");
ResultSet rs = null;
try{
Statement stmt = con.createStatement();
System.out.println("Statement Created");
String query = "query to get data from db";
rs = stmt.executeQuery(query);
System.out.println("Query executed");
ResultSetMetaData metadata = rs.getMetaData();
}catch (Exception e) {
System.out.println("Error.......: "+e);
}
// Storing the database data into the excel
for(int i=0; rs.next();i++) {
// First column
addLabel(sheet, 0, i, rs.getString(1));
}
rs.close();
}
private void createContent(List<String> list, WritableSheet sheet, int columnNumber) throws Exception {
for(int i=0; i<list.size();i++) {
// First column
addLabel(sheet, columnNumber, i, list.get(i).toString());
}
}
private void addCaption(WritableSheet sheet, int column, int row, String s) throws Exception {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addLabel(WritableSheet sheet, int column, int row, String s) throws Exception {
Label label;
label = new Label(column, row, s, times);
sheet.addCell(label);
}
public void read() throws Exception {
File inputWorkbook = new File(inputFile);
empIDs = new ArrayList<String>();
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first column up to 10 rows
for(int i=0;i<sheet.getRows();i++) {
Cell cell = sheet.getCell(0, i);
CellType type = cell.getType();
if (type == CellType.LABEL) {
empIDs.add(cell.getContents());
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
OneMore test = new OneMore();
// Retrieving Data from the Database and storing in the First Excel
test.setOutputFile("C:\\NotBackedUp\\OxygenWorkspace\\HelloSelenium\\src\\main\\resources\\test\\FirstExcel.xls");
test.write(0);
test.retrieveDataFromDBAndStoreItInExcel(test.excelSheet);
test.workbook.write();
test.workbook.close();
System.out.println("=> The First Excel Writing task completed...");
// Reading data from the First Excel and storing it in empIDs ArrayList
test.read();
System.out.println("=> The Excel Data is : "+test.empIDs);
// You use empIDs ArrayList which has emp ids for getting the invoice details from the Application and store it in the invoiceDetails ArrayList below
test.invoiceDetails = new ArrayList<String>();
test.invoiceDetails.add("Invoice Details from the Application");
// Writing the Invoice Details and the emp id Data to the Second Excel
test.setOutputFile("C:\\NotBackedUp\\OxygenWorkspace\\HelloSelenium\\src\\main\\resources\\test\\SecondExcel.xls");
test.write(0);
test.createContent(test.invoiceDetails, test.excelSheet, 0);
test.createContent(test.empIDs, test.excelSheet, 1);
test.workbook.write();
test.workbook.close();
}
}
Я впервые попробовал использовать jxl, поэтому я протестировал чтение и запись данных в Excel в своей системе и работал как ожидалось.
Но у меня нетне проверял часть базы данных и все, поэтому попробуйте изменить / выполнить, следуя комментариям в методе main ().Вам не нужно ничего кодировать, просто вам нужно изменить некоторые детали конфигурации и пути к именам файлов Excel в соответствии с вашими требованиями.
Надеюсь, это поможет ... Счастливое кодирование ...