Вы находитесь на странице: 1из 2

package sampleproject1.

sampleproject1;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;

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 org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook.*;
import org.apache.xmlbeans.XmlLanguage;

public class Testthree {


static DecimalFormat df = new DecimalFormat("#####0");

public static void main(String[] args) {


FileWriter fostream;
PrintWriter out = null;
String strOutputPath = "C:\\Users\\I2642\\workspace\\Task1";
String strFilePrefix = "TestExcel";

try {

FileInputStream inputStream = new FileInputStream(


new
File("C:\\Users\\I2642\\workspace\\Task1\\TestExcel.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);
fostream = new FileWriter(strOutputPath + "\\" + strFilePrefix +
".xml");
out = new PrintWriter(new BufferedWriter(fostream));

out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");


out.println("<Suite>");

boolean firstRow = true;


for (Row row : sheet) {
if (firstRow == true) {
firstRow = false;
continue;
}
out.println("\t<DCT>");
out.println(formatElement("\t\t", "TC_Num",
formatCell(row.getCell(0))));
out.println(formatElement("\t\t", "TC_Desc",
formatCell(row.getCell(1))));
out.println(formatElement("\t\t", "State",
formatCell(row.getCell(2))));
out.println(formatElement("\t\t", "Duration",
formatCell(row.getCell(3))));
out.println("\t</DCT>");
}
out.write("</Suite>");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private static String formatCell(Cell cell) {


if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
return "";
case Cell.CELL_TYPE_BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case Cell.CELL_TYPE_ERROR:
return "*error*";
case Cell.CELL_TYPE_NUMERIC:

return df.format(cell.getNumericCellValue());

case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default:
return "<unknown value>";
}
}

private static String formatElement(String prefix, String tag, String value)


{
StringBuilder sb = new StringBuilder(prefix);
sb.append("<");
sb.append(tag);
if (value != null && value.length() > 0) {
sb.append(">");
sb.append(value);
sb.append("</");
sb.append(tag);
sb.append(">");
} else {
sb.append("/>");

return sb.toString();
}
return value;

}
}

Вам также может понравиться