Download jxl and use this code
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.swing.text.BadLocationException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Font;
import jxl.read.biff.BiffException;
public class XlsToXml {
public String toXml(File excelFile) throws IOException, BiffException {
try {
String xmlLine = "";
String rowText = "";
String colText = "";
String isBold = "";
Font font = null;
String cellCol = "";
String cellAddress = "";
Cell cell = null;
Workbook workbook = Workbook.getWorkbook(excelFile);
xmlLine += "<workbook>" + "n";
for (int sheet = 0; sheet < workbook.getNumberOfSheets(); sheet++) {
Sheet s = workbook.getSheet(sheet);
xmlLine += " <sheets>" + "n";
Cell[] row = null;
for (int i = 0; i < s.getRows(); i++) {
row = s.getRow(i);
for (int j = 0; j < row.length; j++) {
if (row[j].getType() != CellType.EMPTY) {
cell = row[j];
cellCol=columnName(cell.getColumn());
cellCol=" colLetter=""+cellCol+""";
cellAddress=" address=""+cellAddress(cell.getRow()+1,cell.getColumn())+""";
isBold = cell.getCellFormat().getFont().getBoldWeight() == 700 ? "true" : "false";
isBold = (isBold == "false" ? "" : " isBold="true"");
colText += " <col number="" + (j + 1) + """ + isBold +cellAddress+ ">";
colText += "<![CDATA[" + cell.getContents() + "]]>";
colText += "</col>" + "n";
rowText += cell.getContents();
}
}
if (rowText != "") {
xmlLine += " <row number="" + (i + 1) + "">" + "n";
xmlLine += colText;
xmlLine += " </row>" + "n";
}
colText = "";
rowText = "";
}
xmlLine += " </sheet>" + "n";;
}
xmlLine += "</workbook>";
return xmlLine;
} catch (UnsupportedEncodingException e) {
System.err.println(e.toString());
}
return null;
}
private String cellAddress(Integer rowNumber, Integer colNumber){
//return "$"+columnName(colNumber)+"$"+rowNumber;
return columnName(colNumber)+rowNumber;
}
private String columnName(Integer colNumber) {
Base columns = new Base(colNumber,26);
columns.transform();
return columns.getResult();
}
class Base {
String[] colNames = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");
String equalTo;
int position;
int number;
int base;
int[] digits;
int[] auxiliar;
public Base(int n, int b) {
position = 0;
equalTo = "";
base = b;
number = n;
digits = new int[1];
}
public void transform() {
if (number < base) {
digits[position] = number;
size();
} else {
digits[position] = number % base;
size();
position++;
number = number / base;
transform();
}
}
public String getResult() {
for (int j = digits.length - 2; j >= 0; j--) {
equalTo += colNames[j>0?digits[j]-1:digits[j]];
}
return equalTo;
}
private void size() {
auxiliar = digits;
digits = new int[auxiliar.length + 1];
System.arraycopy(auxiliar, 0, digits, 0, auxiliar.length);
}
}
}
carlwils
Posted on Apr 7, 2022
• Updated on Apr 22, 2022
Office OpenXML, also known as OpenXML or OOXML, is a zipped, XML-based format developed by Microsoft. It can include Word documents, Excel spreadsheets, PowerPoint presentations, and Charts, Diagrams, Shapes, etc. This article will share how to Convert Excel to Office Open XML and then convet it back using a free Java library named Free Spire.XLS for Java.
Install the free library (2 Method)
1# Download the free library and unzip it, then add the Spire.Xls.jar file to your project as dependency.
2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Enter fullscreen mode
Exit fullscreen mode
Convert Excel to Office Open XML Using Java
Free Spire.XLS for Java offers the Workbook.saveAsXml() method to save the Excel file as Office Open XML.
import com.spire.xls.Workbook;
public class ExcelToOpenXML {
public static void main(String []args){
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load an Excel file
workbook.loadFromFile("Sales1.xlsx");
//Save as Office Open XML file format
workbook.saveAsXml("ToXML.xml");
}
}
Enter fullscreen mode
Exit fullscreen mode
Convert Office Open XML to Excel in Java
Using the Workbook.saveToFile() method, you can save the Office Open XML file as Excel.
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
public class OpenXmlToExcel {
public static void main(String []args){
//Create an instance of Workbook class
Workbook workbook = new Workbook();
//Load an Office Open XML file
workbook.loadFromXml("ToXML.xml");
//Save as Excel XLSX file format
workbook.saveToFile("ToExcel.xlsx", ExcelVersion.Version2016);
}
}
Enter fullscreen mode
Exit fullscreen mode
Office Open XML (also referred to as OOXML) is a zipped, XML-based format for Excel, Word and Presentation documents. Sometimes, you may need to convert an Excel file to Office Open XML in order to make it readable on various applications and platforms. Likewise, you might also want to convert Office Open XML to Excel for data calculations. In this article, you will learn how to Convert Excel to Office Open XML and vice versa in Java using Spire.XLS for Java library.
- Convert Excel to Office Open XML in Java
- Convert Office Open XML to Excel in Java
Install Spire.XLS for Java
First of all, you’re required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project’s pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>13.4.1</version> </dependency> </dependencies>
Convert Excel to Office Open XML in Java
The following are the steps to convert an Excel file to Office Open XML:
- Create an instance of Workbook class.
- Load an Excel file using Workbook.loadFromFile() method.
- Call Workbook.saveAsXml() method to save the Excel file as Office Open XML.
- Java
import com.spire.xls.Workbook; public class ExcelToOpenXML { public static void main(String []args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("Sample.xlsx"); //Save as Office Open XML file format workbook.saveAsXml("ToXML.xml"); } }
Convert Office Open XML to Excel in Java
The following are the steps to convert an Office Open XML file to Excel:
- Create an instance of Workbook class.
- Load an Office Open XML file using Workbook.loadFromXml() file.
- Call Workbook.saveToFile() method to save the Office Open XML file as Excel.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; public class OpenXmlToExcel { public static void main(String []args){ //Create an instance of Workbook class Workbook workbook = new Workbook(); //Load an Office Open XML file workbook.loadFromXml("ToXML.xml"); //Save as Excel XLSX file format workbook.saveToFile("ToExcel.xlsx", ExcelVersion.Version2016); } }
Apply for a Temporary License
If you’d like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
1
branch
0
tags
Code
-
Use Git or checkout with SVN using the web URL.
-
Open with GitHub Desktop
-
Download ZIP
Latest commit
Files
Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
ExcelToXmlConversion
This code will convert A Excel File to XML File In Java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.DataFormatter;
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 ExcelToXmlConversion {
public static void convertToXml(File excelfile) {
File xmlfile=new File(excelfile.toString().replaceAll(".xlsx", ".xml"));
Workbook workbook;
Sheet sheet;
FileWriter fw=null;
DataFormatter dataformatter=new DataFormatter();
try {
//To create XML File in same folders.
if(!xmlfile.exists()){
xmlfile.createNewFile();
}
//Create Workbook Object to represent Excel file.
workbook = new XSSFWorkbook(excelfile);
sheet=workbook.getSheetAt(0);
fw=new FileWriter(xmlfile);
//Obtain first row(Header Row)
Row firstrow=sheet.getRow(0);
//Name of root element
fw.write("<name of root element>n");
for(int i=1;i<=sheet.getLastRowNum();i++){
Row remrows=sheet.getRow(i);
//Name of Element
fw.write("t<Name of Element>n");
for(int j=0;(j<firstrow.getLastCellNum() && j<remrows.getLastCellNum());j++){
fw.write("tt<"+firstrow.getCell(j)+">"+dataformatter.formatCellValue(remrows.getCell(j))+"</"+firstrow.getCell(j)+">n");
}
fw.write("t</Name of Element>n");
}
fw.write("</name of root element>n");
} catch (InvalidFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String [] args) {
File xmlfile=new File("Path of Excel File");
ExcelToXmlConversion.convertToXml(xmlfile);
}
Содержание
- Работа с Excel в Java через Apache POI
- Подготовка: загрузка библиотек и зависимостей
- Запись
- Чтение
- Apache POI – Read and Write Excel File in Java
- 1. Maven Dependency
- 2. Important Classes in POI Library
- HSSF, XSSF and XSSF classes
- Row and Cell
- Styling Related Classes
- FormulaEvaluator
- 3. Writing an Excel File
- 4. Reading an Excel File
- 5. Add and Evaluate Formula Cells
- 6. Formatting the Cells
- 6.1. Cell value in a specific range
- 6.2. Highlight Duplicate Values
- 6.3. Alternate Color Rows in Different Colors
- 6.4. Color amounts that are going to expire in the next 30 days
- 7. Conclusion
- Web technologies
- Read Excel file
- Write XML
- Normalizing sheet names and column headers
- Quick overview of XSLX format
- Whole code
- How to convert Excel to XML using java?
- 5 Answers 5
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to read/write XML maps from/in excel with Apache POI in Java?
- 1 Answer 1
Работа с Excel в Java через Apache POI
Из этой статьи вы сможете узнать о записи и чтении данных из Excel файлов в Java (будет рассмотрен как XLS , так и XLSX формат). Мы будем использовать библиотеку Apache POI и сосредоточимся на работе с типами String и Date , работа с последним происходит достаточно хитро. Напомню, что работу с числами мы уже рассмотрели в другой статье.
Библиотеку poi-XX.jar вы можете использовать для всех старых ( xls , doc , ppt ) файлов Microsoft Office, для новых ( xlsx , docx , pptx ) вам понадобится poi-ooxml-XX.jar . Очень важно понимать, что к чему относится, т.к. используемые классы тоже разные — для старых расширений это HSSFWorkbook , а для новых — XSSFWorkbook .
Подготовка: загрузка библиотек и зависимостей
Конечно, существует достаточно много открытых библиотек, которые позволяют работать с Excel файлами в Java, например, JXL, но мы будем использовать имеющую самый обширный API и самую популярную — Apache POI. Чтобы её использовать, вам нужно скачать jar файлы и добавить их через Eclipse вручную, или вы можете предоставить это Maven.
Во втором случае вам нужно просто добавить следующие две зависимости:
Самое удобное в Maven — что он загрузит не только указанные poi.jar и poi-ooxml.jar , но и все jar файлы, которые используются внутри, то есть xmlbeans-2.6.0.jar , stax-api-1.0.1.jar , poi-ooxml-schemas-3.12.jar и commons-codec-1.9.jar .
Если вы будете добавлять библиотеки вручную — не забудьте о вышеназванных файлах. Скачать всё можно отсюда. Помните — если вы загрузите только poi-XX.jar , то ваш код скомпилируется без ошибок, но потом упадёт с java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject , так как внутри будет вызываться xmlbeans.jar .
Запись
В этом примере мы запишем в xls файл следующие данные: в первую ячейку — строку с именем, а во вторую — дату рождения. Вот пошаговая инструкция:
- Создаём объект HSSFWorkBook ;
- Создаём лист, используя на объекте, созданном в предыдущем шаге, createSheet() ;
- Создаём на листе строку, используя createRow() ;
- Создаём в строке ячейку — createCell() ;
- Задаём значение ячейки через setCellValue();
- Записываем workbook в File через FileOutputStream ;
- Закрываем workbook , вызывая close() .
Для записи строк или чисел этого вполне достаточно, но чтобы записать дату, нам понадобится сделать ещё кое-что:
- Создать DateFormat ;
- Создать CellStyle ;
- Записать DateFormat в CellStyle ;
- Записать CellStyle в ячейку;
- Теперь в эту ячейку можно записать объект Date через всё тот же setCellValue ;
- Чтобы дата поместилась в ячейку, нам нужно добавить столбцу свойство автоматически менять размер: sheet.autoSizeColumn(1) .
Всё вместе это будет выглядеть так:
Чтение
Теперь мы считаем из только что созданного файла то, что мы туда записали.
- Для начала создадим HSSFWorkBook , передав в конструктор FileInputStream ;
- Получаем лист, передавая в getSheet() его номер или название;
- Получаем строку, используя getRow() ;
- Получаем ячейку, используя getCell() ;
- Узнаём тип ячейки, используя на ней getCellType() ;
- В зависимости от типа ячейки, читаем её значения, используя getStringCellValue() , getNumericCellValue() или getDateCellValue() ;
- Закрываем workbook используя close() .
Напомню, что дату Excel хранит как числа, т.е. тип ячейки всё равно будет CELL_TYPE_NUMERIC .
В виде кода это будет выглядеть следующим образом:
Источник
Apache POI – Read and Write Excel File in Java
Last Updated: October 1, 2022
Learn to read excel, write excel, evaluate formula cells and apply custom formatting to the generated excel files using Apache POI library with examples.
If we are building software for the HR or Finance domain, there is usually a requirement for generating excel reports across management levels. Apart from reports, we can also expect some input data for the applications coming in the form of excel sheets and the application is expected to support this requirement.
Apache POI is a well-trusted library among many other open-source libraries to handle such usecases involving excel files. Please note that, in addition, we can read and write MS Word and MS PowerPoint files also using the Apache POI library.
This Apache POI tutorial will discuss some everyday excel operations in real-life applications.
1. Maven Dependency
If we are working on a maven project, we can include the Apache POI dependencies in pom.xml file using this:
2. Important Classes in POI Library
HSSF, XSSF and XSSF classes
Apache POI main classes usually start with either HSSF, XSSF or SXSSF.
- HSSF – is the POI Project’s pure Java implementation of the Excel 97(-2007) file format. e.g., HSSFWorkbook, HSSFSheet.
- XSSF – is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g., XSSFWorkbook, XSSFSheet.
- SXSSF (since 3.8-beta3) – is an API-compatible streaming extension of XSSF to be used when huge spreadsheets have to be produced and heap space is limited. e.g., SXSSFWorkbook, SXSSFSheet. SXSSF achieves its low memory footprint by limiting access to the rows within a sliding window, while XSSF gives access to all rows in the document.
Row and Cell
Apart from the above classes, Row and Cell interact with a particular row and a particular cell in an excel sheet.
FormulaEvaluator
Another helpful class FormulaEvaluator is used to evaluate the formula cells in an excel sheet.
3. Writing an Excel File
I am taking this example first so we can reuse the excel sheet created by this code in further examples.
Writing excel using POI is very simple and involves the following steps:
- Create a workbook
- Create a sheet in workbook
- Create a row in sheet
- Add cells to sheet
- Repeat steps 3 and 4 to write more data
It seems very simple, right? Let’s have a look at the code doing these steps.
Java program to write an excel file using Apache POI library.
4. Reading an Excel File
Reading an excel file using POI is also very simple if we divide this into steps.
- Create workbook instance from an excel sheet
- Get to the desired sheet
- Increment row number
- iterate over all cells in a row
- repeat steps 3 and 4 until all data is read
Let’s see all the above steps in code. I am writing the code to read the excel file created in the above example. It will read all the column names and the values in it – cell by cell.
Java program to read an excel file using Apache POI library.
5. Add and Evaluate Formula Cells
When working on complex excel sheets, we encounter many cells with formulas to calculate their values. These are formula cells. Apache POI also has excellent support for adding formula cells and evaluating already present formula cells.
Let’s see one example of how to add formula cells in excel?
The sheet has four cells in a row and the fourth one in the multiplication of all the previous 3 rows. So the formula will be: A2*B2*C2 (in the second row)
Java program to add formula in an excel file using Apache POI library.
Similarly, we want to read a file with formula cells and use the following logic to evaluate formula cells.
Java program to evaluate formula in an excel file using Apache POI library.
6. Formatting the Cells
So far we have seen examples of reading/writing and excel files using Apache POI. But, when creating a report in an excel file, it is essential to add formatting on cells that fit into any pre-determined criteria.
This formatting can be a different coloring based on a specific value range, expiry date limit etc.
In the below examples, we are taking a couple of such cell formatting examples for various purposes.
6.1. Cell value in a specific range
This code will color any cell in a range whose value is between a configured range. [e.g., between 50 and 70]
6.2. Highlight Duplicate Values
Highlight all cells which have duplicate values in observed cells.
6.3. Alternate Color Rows in Different Colors
A simple code to color each alternate row in a different color.
6.4. Color amounts that are going to expire in the next 30 days
A handy code for financial projects which keeps track of deadlines.
I am ending this apache poi tutorial here to keep the post within a limit.
7. Conclusion
In this tutorial, we learned to read excel, write excel, set and evaluate formula cells, and format the cells with color codings using the Apache POI library.
Источник
Web technologies
Excel is a human readable and writable format, and XML is an important machine language. We need an efficient bridge between those two technologies.
Since 2007, the Excel files are a zip file containing XML data. Those XML files must be serialized into a minimal XML containing the cells data inside tags with the column headers as names. The resulting XML will look like that :
Here is the code to do it.
Read Excel file
In that post, I only treat the case of the recent XLSX format. I will use Apache POI and I want it to be able to manage very big files, so I have to use an event API.
The POI streaming API only treats the old XLS format. For XLSX, you have to use the SAX API which only helps you providing access to a stream of the XML of the sheets. The reading of the tags must be coded into your SAX handler and the given example is very useful but not complete.
The code in order to open a file and trigger the SAX reading is :
Write XML
As I said, I want that serializer to be fast. So I will not use a XML API in order to write the XML output. With some lines of codes, I write the content as a XML containing a namespace for reusability.
Here is the code :
Normalizing sheet names and column headers
In order to avoid issues with XML tag names, I normalize the sheet names and the column headers I found. It removes accents, normalizes spaces, and omits any characters which is not a letter, ‘_’ or a digit.
Here is the normalizing code :
Quick overview of XSLX format
The contents of the cells are inside the tag of the XML files of the sheets.
In the files I use, I saw 3 different structures :
- one with attribute t=»inlineStr» :
- a structure with the value in clear, with attribute t=»n» :
- and a last case, where it uses the “shared strings”. In that case the value is the index of the String in that list of shared strings :
I did not see any tag , as it is expected in example from Apache POI. And in the case of an attribute t=»inlineStr» , the value is in a tag instead of , as expected in example.
Whole code
You can download the whole code here :
FastXlsx2XmlSerializer
Источник
How to convert Excel to XML using java?
i want to convert my input Excel file into the Output XML file.
If anybody has any solution in java for how to take input Excel file and how to write to XML as output,please give any code or any URL or any other solution.
5 Answers 5
Look into the jexcel or Apache POI libraries for reading in the Excel file.
Creating an XML file is simple, either just write the XML out to a file directly, or append to an XML Document and then write that out using the standard Java libs or Xerces or similar.
I have done conversion of Excel(xlsx) to xml in Java recently. I assumed each row in excel as a single object here. Here are the steps I followed:-
- Read Excel file using Apache POI
- Created a xsd file and generated corresponding classes
- Read each row created, created corresponding objects and initilaized values using the generated getter/setter methods in the classes
- Added the objects to an arraylist which holds only objects the same type
- Using Jaxb Marshelled the arraylist object to an output file
JExcel was easy for me to use. Put jxl.jar on the classpath and code something like:
Download jxl and use this code
Linked
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
How to read/write XML maps from/in excel with Apache POI in Java?
A little bit of context, in excel there is a tab named Developer, where you can see/add XML maps in the current workbook:
I am working with Apache POI and I want to read and also write XML maps in excel.
Do you know where can I found documentation regarding on how to read/write XML maps in excel using Apache POI?
1 Answer 1
To read XML mappings from existing workbooks there are API methods available.
There is XSSFWorkbook.getMapInfo which gets the MapInfo. And there is XSSFWorkbook.getCustomXMLMappings which gets a List of all the XSSFMap. So reading should not be the problem.
But until now there is nothing to create new MapInfo and/or putting additional schemas and/or maps in that MapInfo . So to create a new workbook having XML mappings using the low level underlaying objects is necessary.
The following complete example shows this. It provides methods to create a MapInfo and add schemas and maps to it. It uses the following class.xsd file as schema definition:
It creates a MapInfo , adds the schema and the map and creates a XSSFMap . Then it creates a XSSFTable in first scheet which refers to the map. So it is possible collecting data in that table to export as XML then.
Источник
Java converts Excel to XML format output
tags: java programming java
package shuju;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ShuJu {
public static void main(String[] args) throws Exception {
InputStream inp = new FileInputStream(new File("F:\123\Workbook2.xlsx"));
List<Map<String, String>> list=readExcel(inp,"");
dealList(list);
}
/**
* Read the content of the Excel file
* @param inputStream excel file, passed in as InputStream
* @param sheetName sheet name
* @return returns the content in excel as a List
*/
public static List<Map<String, String>> readExcel(InputStream inputStream, String sheetName) {
//Define workbook
XSSFWorkbook xssfWorkbook = null;
try {
xssfWorkbook = new XSSFWorkbook(inputStream);
} catch (Exception e) {
System.out.println("Excel data file cannot be found!");
}
//Define worksheet
XSSFSheet xssfSheet;
if (sheetName.equals("")) {
// Take the first subtable by default
xssfSheet = xssfWorkbook.getSheetAt(0);
} else {
xssfSheet = xssfWorkbook.getSheet(sheetName);
}
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
int maxRow =xssfSheet.getLastRowNum();
//The default first line is the title line, index = 0
XSSFRow titleRow = xssfSheet.getRow(0);
//System.out.println("The total number of rows is:" + maxRow);
for (int row = 1; row <= maxRow; row++) {
XSSFRow xss=xssfSheet.getRow(row);
if(xss!=null){
int maxRol = xssfSheet.getRow(row).getLastCellNum();
//System.out.println("--------The data of the first "+ row +" line is as follows--------");
Map<String, String> map = new LinkedHashMap<String, String>();
for (int rol = 1; rol < maxRol; rol++){
XSSFCell cell=xssfSheet.getRow(row).getCell(rol);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
//System.out.print(cell.getStringCellValue());
map.put(titleRow.getCell(rol).getStringCellValue(),cell.getStringCellValue());
}
//System.out.println();
list.add(map);
}
}
//System.out.println();
int i=1;
for(Map<String, String> map1:list){
//System.out.print(i+" ");
for (Object key : map1.keySet()) {
//System.out.print(" "+key+":"+map1.get(key));
}
//System.out.println();
i++;
}
return list;
}
public static void dealList(List<Map<String, String>> list){
for(Map<String, String> map:list){
StringBuffer sb=new StringBuffer();
sb.append("<?xml version="1.0" encoding="UTF-8"?>n");
sb.append("<XMLMESSAGE>n");
sb.append("<TICKET>n");
sb.append(" <TICHEAD>n");
sb.append(" <Sid>"+map.get("SERIALNO")+"</Sid>n");
sb.append(" <SubSid></SubSid>n");
sb.append(" <UserId></UserId>n");
sb.append(" <RegNo>"+map.get("USERACCOUNT")+"</RegNo>n");
sb.append(" <OTime></OTime>n");
sb.append(" <AreaCode>"+map.get("AREANO")+"</AreaCode>n");
sb.append(" <SLA></SLA>n");
sb.append(" <Pid></Pid>n");
sb.append(" <TicType>"+map.get("ORDERTYPE")+"</TicType>n");
sb.append(" <MachType></MachType>n");
sb.append(" <DevKey></DevKey>n");
sb.append(" <MachType_Old></MachType_Old>n");
sb.append(" <DevKey_Old></DevKey_Old>n");
sb.append(" </TICHEAD>n");
sb.append(" <TICBODY>n");
sb.append(" <Service>n");
sb.append(" <SvcId></SvcId>n");
sb.append(" <Oper>"+map.get("OPERATETYPE")+"</Oper>n");
sb.append(" <Sequence></Sequence>n");
for(int i=1;i<=20;i++){
String paraname="attr"+i;
sb.append(" <Resource>n");
sb.append(" <ParaName>"+paraname+"</ParaName>n");
sb.append(" <NewValue>"+map.get(paraname.toUpperCase())+"</NewValue>n");
sb.append(" </Resource>n");
}
for(int i=1;i<=20;i++){
String paraname="attr"+i+"_old";
sb.append(" <Resource>n");
sb.append(" <ParaName>"+paraname+"</ParaName>n");
sb.append(" <NewValue>"+map.get(paraname.toUpperCase())+"</NewValue>n");
sb.append(" </Resource>n");
}
sb.append(" </Service>n");
sb.append(" </TICBODY>n");
sb.append("</TICKET>n");
sb.append("</XMLMESSAGE>n");
if("60".equals(map.get("ORDERTYPE")))
System.out.println(sb.toString());
}
}
}
Intelligent Recommendation
Java converts Excel to images, html, XPS, XML, CSV
Through document format conversion, it can meet the requirements of document operation in different office situations. This article will introduce how to convert Excel documents to other common docume…
Java exports data in bulk, in xml or excel format.
The large data volume export function is used in recent projects. It is not certain how big, at least ten thousand records. 100M excel file, excel2003 can not be opened, can only use the 2007 version….
Java string-XML formatted output format
1.Html Add XMP tag, JavaScript triggers Ajax, 2. Background converts the String type MSG into XML format, returns to the HTML XMP tab 3. Define the button Clean situation MSG content…
More Recommendation
xStream converts xml into object format
converted xml file First, you should first write a java object with the same properties as the xml file. Second, the conversion Note the filling and encoding of the root node alias…
Python converts Excel into JSON format
JSON (JavaScript Object Notation) is a lightweight data exchange format, a concise and clear hierarchy that makes it an ideal data exchange language, easy to read and prepare, and it is also easy to a…
Copyright DMCA © 2018-2023 — All Rights Reserved — www.programmersought.com User Notice
Top
Having your important data available to you whenever you need it will increase your efficiency and boost your overall productivity. For large amounts of data such as invoices or other tracked transactions that can be logged continuously for years, trying to find one instance in a massive Excel spreadsheet is not the ideal solution. Instead, by converting your data to JSON or XML, you can transfer these logs to a computer program that can then be accessed by anyone with permission and simplify the data retrieval process.
However, to do this, your data needs to be placed in a machine-readable format that will be easily understood by your computer systems. For example, much of your data is likely saved in an Excel or CSV file format, as these are the most familiar and user-friendly static data formats. However, data from these programs cannot be easily transferred to an online format that might be necessary for certain applications used by your organization. Thus, a data interchange format like JSON or XML is required for accessibility.
JavaScript Object Notation, or JSON, is a widely used data-interchange format used to store and exchange data for widescale usage. It is also a self-describing system, where the variables for your data can be created at will, without limiting factors. Our other option, Extensible Markup Language (XML), is like JSON in that both humans and computers can easily read it. Still, it mainly uses prescribed tags that divide information according to its traits. Thus, XML appears very similar to HTML in its code formatting. Though it uses more descriptive words than JSON, XML allows for higher specificity in how data is read by the computer, including improved metadata usability. In essence, when working on the browser-side, JSON is preferred, while XML is ideal for working server-side.
The following four APIs will allow you to convert your data sets from Excel and CSV to JSON and XML. This will allow you to improve the accessibility of your data and increase the efficiency with which your system receives, read, and process your information for further use.
You will first need to install the SDK library using Maven or Gradle for all of these functions. To install with Maven, you can add a Jitpack reference to the repository in pom.xml:
Then, add a reference to the dependency:
To install with Gradle, you can add the reference to your root build.gradle at the end of repositories:
Then, you can add the dependency in build.gradle:
The first API will instantly convert an Excel XLSX file to JSON. Once you have installed the SDK as shown above, you can add the imports to the top of the file and call the function:
This will return an output JSON string that can be read using any text file viewer. To ensure that this API works properly, you need to ensure certain requirements are met:
- The XLSX file is valid and inputs correctly.
- You have input your API Key. This can be retrieved at no cost on the Cloudmersive website, providing 800 monthly calls across our API library.
The second API will convert your data from CSV to JSON. Similar to the first function, you will need to input your CSV file. However, you can also specify whether the first row in your CSV file will be used as column names. The default for this parameter is true, but if selected as false, the column names will appear as Column0, Column1, etc.
As before, install the SDK, add the imports to the file, and call the function:
These next two APIs will convert your data to XML, with the first converting from XLSX. Install the SDK library and then call the function:
Finally, to convert from CSV to XML, you can call the following function:
With these functions, you can easily optimize your data for use wherever and whenever you need it. If you have any questions about using these APIs or inquiries concerning other API solutions, you can visit the Cloudmersive website, where our team is happy to help with anything you might need.
Opinions expressed by DZone contributors are their own.