Java語言是一種非常流行的編程語言,它在許多不同的領域得到了廣泛的應用。其中,Java開發人員經常需要將Excel文件轉換為JSON格式。這可以通過使用Java編寫代碼來完成。下面是一個簡單的示例,說明如何使用Java將Excel文件轉換為JSON格式。
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; 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.ss.usermodel.WorkbookFactory; import com.fasterxml.jackson.databind.ObjectMapper; public class ExcelToJsonConverter { public static void main(String[] args) throws IOException { // create input stream to read the excel file InputStream in = new FileInputStream(new File("sample.xlsx")); // create a workbook object Workbook workbook = WorkbookFactory.create(in); // get the first sheet from the workbook Sheet sheet = workbook.getSheetAt(0); // create a list to save the rows of the sheet List rows = new ArrayList<>(); // iterate through the rows of the sheet IteratorrowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); // create a list to save the cells of the row List cells = new ArrayList<>(); // iterate through the cells of the row Iterator
cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // add the cell value to the list cells.add(cell.getStringCellValue()); } // add the row cells to the rows list rows.add(cells); } // create a JSON object mapper ObjectMapper mapper = new ObjectMapper(); // convert the rows list to a JSON string String json = mapper.writeValueAsString(rows); // print the JSON string System.out.println(json); // close the input stream and workbook objects in.close(); workbook.close(); } } |
以上代碼示例中,使用了Apache POI庫來讀取Excel文件中的數據,并使用Jackson庫將Excel數據轉換為JSON格式。同時,還使用了Java中的集合來保存Excel表格中的數據,并對其進行迭代處理。通過上述代碼示例,可以快速地將Excel文件轉換為JSON格式,以便于在編程中進行使用。