我编写了一个 Java 程序来从 SQL 中获取数据并将其写入 Excel 表,以下程序仅在我取消注释我不知道为什么会这样的行时才有效,请帮助我更正程序。
package com.selenium.examples;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.poi.ss.usermodel.Cell;
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;
public class SQLtoExcelSheet {
public static void main(String[] args) throws SQLException, IOException {
Workbook excel=new XSSFWorkbook();
Sheet sheet= excel.createSheet("SQLResults");
int excelRowNo=0;
int excelCellNo=0;
String connectionUrl = "jdbc:sqlserver://localhost;user=sa;password=abc@123";
Connection con=DriverManager.getConnection(connectionUrl);
Statement stmt=con.createStatement();
String SQL="use BonusingCore;"+"select * from MachineMaster;";
ResultSet result=stmt.executeQuery(SQL);
ResultSetMetaData mataData=result.getMetaData();
int columnCount=mataData.getColumnCount();
result.next();
//first row should be Column label
for(int sqlColumnNumber=1;sqlColumnNumber<=columnCount;sqlColumnNumber++ ){
Row excelRow=sheet.createRow(excelRowNo);
Cell excelCell=excelRow.createCell(excelCellNo);
excelCell.setCellValue(mataData.getColumnName(sqlColumnNumber));
excelCellNo++;
excelRowNo++;
sheet.autoSizeColumn(excelCellNo);
}
FileOutputStream flout=new FileOutputStream("C:\\Users\\Illusion\\workspace\\SeleniumExamples\\testData\\output.xlsx");
excel.write(flout);
flout.close();
}
}