[英]Reading cells from an Existing Excel File and Writing them into a new Excel File using Java
因此,我目前正在使用JXL Java庫創建一個程序,以將現有Excel文件中的數據讀取,編輯和放置到新的Excel文件中。 在這一階段,我只想從現有的Excel文件中讀取數據並將其放入新文件中。 似乎找不到一種很好的方式來做,對於將來的工作,什么是編輯數據(具有某些列)並將其放置到新的Excel文件中的最佳方法是什么。
抱歉,如果還不清楚,請立即熟悉Java和Stackoverflow。
import java.io.*;
import jxl.*;
import jxl.write.Number;
import jxl.write.*;
class Extraction {
private String inputFile;
String data;
public void setInputFile(String inputFile){
this.inputFile = inputFile;
}
public void read() throws IOException {
File spreadsheet = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(spreadsheet);
Sheet page = w.getSheet(0);
File f = new File("C:\\Users\\alex\\Desktop\\New_Export.xls");
if (!f.exists()){
String FileName = "C:\\Users\\alex\\Desktop\\New_Export.xls";
WritableWorkbook excel = Workbook.createWorkbook(new File(FileName));
WritableSheet sheet = excel.createSheet("Sheet1", 0);
for (int y = 0; y < page.getRows(); y++){
for (int x = 0; x < page.getColumns(); x++){
Cell cell = page.getCell(x ,y +1);
CellType type = cell.getType();
if(type == CellType.LABEL || type == CellType.NUMBER){
data = cell.getContents();
System.out.println(data);
//To now input the read data into the new Excel File
sheet.addCell();
}
}
System.out.println(" ");
}
System.out.println("The File Has Successfully Been Created!");
excel.write();
excel.close();
}
else{
System.err.println("File is already created!");
}
}
catch(Exception e){
System.out.println(" ");
}
}
public static void main (String args[]) throws IOException{
Extraction reading = new Extraction();
reading.setInputFile("C:\\Users\\alex\\Desktop\\export.xls");
reading.read();
}
}
使用apache中的“ poi”,您可以使用以下代碼讀取excel(* .xls)
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
private void readingExcel(String fileName) {
try (FileInputStream file = new FileInputStream(new File(fileName))) {
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
for (Row row : sheet) {
Iterator<Cell> cellIterator = row.cellIterator();
for (Cell cell : row) {
System.out.println(cell.getStringCellValue());
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
為了寫優秀
private File writingToExcel() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample-sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("My Sample Value");
File file = new File(sheet.getSheetName());
return file;
}
但是,如果要使用* .xlsx,則用於讀取的類為
XSSFWorkbook workbook = new XSSFWorkbook (file);
XSSFSheet sheet = workbook.getSheetAt(0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.