Correct me where I'm going wrong.
I'm have written a program in Java which will get list of files from two different directories and make two (Java list) with the file names. I want to transfer the both the list (downloaded files list and Uploaded files list) to an excel.
What the result i'm getting is those list are transferred row wise. I want them in column wise.
Given below is the code:
public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\report\\02_Download\\10252013");
Path dispatchPath = Paths.get("E:\\report\\01_Dispatch\\10252013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10252013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List> recordToAdd = new ArrayList<>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
F f = new F();
f.CreateExcelFile(recordToAdd);
f.createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<List> l1) throws Exception {
try {
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2 = l1.get(j);
for (int k = 0; k < l2.size(); k++) {
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
} finally {
}
}
}
(The purpose is to verify the files Downloaded and Uploaded for the given date)
Thanks.
If you want to access/build the worksheet in columns instead of rows, you need to change the worksheet accessing code.
Snipped out from your existing code, here are the key functions:
Row row = firstSheet.createRow( rowNum);
Cell cell = row.createCell( colNum);
cell.setCellValue( value);
You need to rearrange those loops to output your data in a column-wise fashion.
Thanks for the suggestions.. I have modified my program and uploaded with the solution.
public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\Download\\10292013");
Path dispatchPath = Paths.get("E:\\Dispatch\\10292013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
/* List all files*/
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10292013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<String>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List<String>> recordToAdd = new ArrayList<List<String>>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
CreateExcelFile(headerRow, download, upload);
createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<String> headers, List<String> down, List<String> up) throws Exception {
try {
Row row = firstSheet.createRow((short)(rownum++));
for(int i = 0;i < headers.size();i++) {
Cell cell = row.createCell(i);
cell.setCellValue(headers.get(i));
}
for (int j = 0; j < down.size(); j++) {
row = firstSheet.createRow((short)(rownum++));
Cell cell = row.createCell(0);
cell.setCellValue(down.get(j));
if(up.size() > j) {
cell = row.createCell(1);
cell.setCellValue(up.get(j));
}
}
} catch (Exception e) {
} finally {
}
}
}
Related
I am trying to unit test this piece of code:
#Slf4j
#Service
#RequiredArgsConstructor
public class LeMigrationService {
private final MigrationServiceClient migrationServiceClient;
public FileUploadRs process(MultipartFile file) {
List<String> listOfCifs = null;
try {
listOfCifs = ExcelUtil.collectColumnByIndex(file, 0);
} catch (Exception e) {
LOGGER.error("Failed to load excel file content " + e);
}
return migrationServiceClient.process(listOfCifs);
}
}
The static method:
public class ExcelUtil {
public static List<String> collectColumnByIndex(MultipartFile file, int index) throws Exception {
List<String> listOfCifs = new ArrayList<>();
Workbook workbook = new XSSFWorkbook(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Cell cell = row.getCell(index);
int cellLength = cell.getStringCellValue().length();
if (cellLength < 9) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 9 - cellLength; i++) {
str.append("0");
}
str.append(cell.getStringCellValue());
listOfCifs.add(str.toString());
}
if (cellLength > 9) {
break;
}
if(cellLength == 9) {
listOfCifs.add(cell.getStringCellValue());
}
}
return listOfCifs;
}
}
And finally my unit test:
#RunWith(MockitoJUnitRunner.class)
public class LeMigrationServiceTest {
#Test
public void processFile_FileContentIsOk() throws Exception{
//arrange
final MockMultipartFile fakeFile = new MockMultipartFile("file", "file.xls", MediaType.TEXT_PLAIN_VALUE, "0123456789".getBytes());
//act
final List<String> actual = ExcelUtil.collectColumnByIndex(fakeFile, 0);
final List<String> expected = new ArrayList<>();
expected.set(0, "0123456789");
//assert
assertThat(actual).isEqualTo(expected);
}
}
When I run the test, I get the error when it calls the static method "collectColumnByIndex". Apparently I do not create well the object "Workbook" inside the method "collectColumnByIndex". Do you have any ideas of how to solve this?
I want to write the output of the displayDirectoryContents to a excel sheet
I have tried using the Apache POI method I want to get the output to a excel sheet
Folder and filename in one column and
the name of the files in another column
import statements
public class Excel {
private static String dest = "C:\\Users\\mahselva\\testexcel.xls";
private static HSSFWorkbook myWorkBook = new HSSFWorkbook();
private static HSSFSheet mySheet = myWorkBook.createSheet();
public static void excelLog(String filename, String message, int rowNum)
{
HSSFRow myRow = null;
HSSFCell myCell = null;
String excelData[][] = new String[1][2];
excelData[0][0] = filename;
excelData[0][1] = message;
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 2; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[0][cellNum]);
}
try {
FileOutputStream out = new FileOutputStream(dest);
myWorkBook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File currentDir = new File("C:\\OracleATS\\openScript"); // current
directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
int i = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
Path path = Paths.get(file.getCanonicalPath());
//System.out.println("Folder"
+path.getFileName().toString());
excelLog("Folder",path.getFileName().toString(),i);
i++;
displayDirectoryContents(file);
} else {
Path path = Paths.get(file.getCanonicalPath());
//System.out.println(path.getFileName().toString());
excelLog("File",path.getFileName().toString(),i);
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want two columns in an excel sheet with column 1 containing File or
Folder and column 2 containing the name of the file/folder
eg
File books.xml
Folder Script
Thus i want to write the output to the excel sheet
i am using the function excel log to write to the output screen
I use this to write to an excel - however I make it .csv format, not xls. Therefore this might not be what you need, but it's still partially useful as it's writing in a file that can be opened by excel efortlessly.
public static void printAtFile(String filename, String header, String content[])
{
filename+=".csv";
System.out.println("Start creating file "+filename);
PrintWriter writer = null;
try {
writer = new PrintWriter(filename);
writer.println(header);
for(String u:content)
writer.println(u);
writer.close();
} catch (Exception ex) {
System.out.println("Error while writing at file "+filename);
}
}
Testcase file. Testcase with fillo query data driven
Suppose when the query (String qry="Select * from Sheet1 where ACC='M' and GEN='F'";) returns 5 data rows for one test case and i want to use the same qry for the next case but with different data row
public class Testcases {
public WebDriver driver;
Fillo fillo;
static ExtentReports report;
ExtentTest test;
//String PAGE_URL = "Your_page_Url";
#BeforeClass public static void allTestsPrep(){
report = new ExtentReports("Report.html",true);
}
#AfterClass public static void allTestCleanUp() {
report.flush();
}
#Before
public void setUp() {
String browserName = getParameter("browser");
if (browserName.equalsIgnoreCase("chrome")){
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();}
else if (browserName.equalsIgnoreCase("ie")) {
driver = new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// driver.get(PAGE_URL);
}
#Test
public void Testcase001() throws FilloException, InterruptedException {
String qry="Select * from Sheet1 where ACC='M' and GEN='F'";
test = report.startTest("Testcase 1 - Test findpage");
Useragreement usragr = new Useragreement(driver);
usragr.CheckboxSelectall();
test.log(LogStatus.PASS, "VERIFIED");//report
}
#After
public void close() {
driver.close();
test = null;
}
private String getParameter(String name) {
String value = System.getProperty(name);
if (value == null)
throw new RuntimeException(name + " is not a parameter!");
if (value.isEmpty())
throw new RuntimeException(name + " is empty!");
return value;
}
}
Fillo file
Now the code will be `FILLO.inputText(Phone_Number,"Pno",qry)``;
public class FILLOAPP {
public static String getTestValue(String fieldName, String qry) throws FilloException{
String testString=xlTesting(fieldName,qry);
return testString;
}
public static String xlTesting(String fieldName, String qry) throws FilloException{
String testval=null;
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("resources/TestData.xlsx");
String sqry=qry;
Recordset recordset=connection.executeQuery(sqry);
while(recordset.next()){
ArrayList<String> dataColl=recordset.getFieldNames();
Iterator<String> dataIterator=dataColl.iterator();
while(dataIterator.hasNext()){
for (int i=0;i<=dataColl.size()-1;i++){
String data=dataIterator.next();
String dataVal=recordset.getField(data);
if (data.equalsIgnoreCase(fieldName)){
String testData=dataColl.get(i);
String testValue= recordset.getField(testData);
testval=testValue;
}
}
break;
}
}
recordset.close();
connection.close();
return testval;
}
public static void inputText(WebElement driver, String fieldName, String qry) throws FilloException{
String fval=getTestValue(fieldName, qry);
driver.sendKeys(fval);
}
}
public String dataRead(String sheetname, String testcaseid, String header) throws IOException {
String value = null;
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
book = new XSSFWorkbook(fis);
sheet = book.getSheet(sheetname);
int lastRowNum = sheet.getLastRowNum();
// System.out.println(lastRowNum);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(lastCellNum);
for (int i = 0; i < lastRowNum; i++) {
for (int j = 1; j < lastCellNum; j++) {
Map<String, Map<String, String>> excelmap = new HashMap<String, Map<String, String>>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i + 1).getCell(j).toString());
excelmap.put(sheet.getRow(i + 1).getCell(0).toString(), map);
if (excelmap.containsKey(testcaseid)) {
Map<String, String> w = excelmap.get(testcaseid);
if (map.containsKey(header)) {
value = w.get(header).toString();
}
}
}
}
} catch (Exception E) {
}
return value;
}
public void excelWrite(String sheetname, String testcaseid, int columnno, String value) throws Throwable {
File file = new File(TESTDATA_SHEET_PATH);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetname);
// sheetnoOfColumns = sheet.getRow(0).getPhysicalNumberOfCells();
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i < lastRowNum; i++) {
Map<Map<String, String>, String> excelmap = new HashMap<Map<String, String>, String>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(0).toString(), sheet.getRow(i + 1).getCell(0).toString());
if (map.containsValue(testcaseid)) {
excelmap.put(map, value);
String w = map.get("TestCase ID");
Map<String, String> fin = new HashMap<String, String>();
fin.put(w, value);
XSSFRow row = sheet.getRow(i + 1);
Cell createcell = row.createCell(columnno);
createcell.setCellValue(value);
}
}
FileOutputStream fileOut = new FileOutputStream(TESTDATA_SHEET_PATH);
workbook.write(fileOut);
fis.close();
fileOut.close();
}
public Map ReadExcelExecution() throws Throwable {
LinkedHashMap<String, Object[]> map = new LinkedHashMap<String, Object[]>();
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("IssuePolicy");
int TotalRow = sheet.getLastRowNum();
int noOfColumns = (sheet.getRow(0).getPhysicalNumberOfCells() - 1);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(TotalRow);
// System.out.println(noOfColumns);
// System.out.println(lastCellNum);
map.put("1",
new Object[] { "TestCase ID", "PolicyNo", "IssueDate", "Accumulated Value", "GMWB Type",
"MAWA/2LMAWA", "Remaining MAWA", "Protected Income Payment", "Accumulated Value DOD",
"DataComparison", "Comments" });
for (int i = 1; i <= TotalRow; i++) {
{
String testcaseid = sheet.getRow(i).getCell(0).toString();
String policyno = sheet.getRow(i).getCell(noOfColumns).toString();
String issuedate = sheet.getRow(i).getCell(2).toString();
String values = null;
map.put(testcaseid, new Object[] { testcaseid, policyno, issuedate, values, values, values, values,
values, values, values, values });
}
}
} catch (Exception E) {
}
return map;
}
public void writinginInputFile(String sheetname, Map mapvalue) throws Throwable {
// write excel file and file name is SaveTestNGResultToExcel.xls
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.createSheet(sheetname);
keyset = mapvalue.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = (Object[]) ReadExcelExecution().get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(TESTDATA_SHEET_PATH));
wb.write(out);
out.close();
System.out.println("Successfully saved Selenium WebDriver TestNG result to Excel File!!!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
}
package seleniumproject;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Multiplewindowpopup {
public static void main(String[] args) {
WebDriver driver;
String Userdir = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",Userdir+"\\Driver\\chromedriver.exe");
driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("http://www.popuptest.com/goodpopups.html");
//find ID of the 2nd link
driver.findElement(By.linkText("Good PopUp #2")).click();
Set<String> windowhandler = driver.getWindowHandles();
Iterator<String> myiterator = windowhandler.iterator();
////////////// //how to get index of parent and child window ???
//now we have two window IDs and moving the window from parent to child.
driver.switchTo().window(childWindow);
System.out.println("child window title"+driver.getTitle());
//closing the child window
driver.close();
// comming back to parentwindow
driver.switchTo().window(parentWindow);
System.out.println("parent window title"+driver.getTitle());
}
}
I have a JSON file in the below format.
{
"applications": [
{
"author": "Appriss, Inc.",
"rating": 4.5,
"isAvailable": true,
"isRecommended": null,
"isEndorsed": false,
"id": "WfIABNya87qyAWABoDivFQ",
"app_name": "MobilePatrol Public Safety App",
"icon_path": "org_5945/android_market_62834/appIcon.png",
"custom_metadata": {
"title": null,
"description": null,
"projects": null,
"category": [
100
],
"user_segment": [
200
],
"aboutApp": null,
"tablet_1_description": null,
"tablet_2_description": null,
"tablet_3_description": null,
"tablet_4_description": null,
"tablet_5_description": null,
"screenshot_1_description": null,
"screenshot_2_description": null,
"screenshot_3_description": null,
"screenshot_4_description": null,
"screenshot_5_description": null,
"endorsement": null,
"developer_description": null,
"developer_website": null
},
"operating_system": "ANDROID",
"app_psk": 62834
},
}
I want to read few of data(like author,rating,app_name etc) into an excel in the form of key/value pair using java. Written below code.
public class JsonParseTest {
private static List<String> header = new ArrayList<String>();
private static List<Row> rows = new ArrayList<Row>();
private static Row row ;-- not able to instantiate this
private static int rowsSize;
public static List<String> getHeader() {
return header;
}
public static List<Row> getRows() {
return rows;
}
public static void main(String[] args) throws IOException, ParseException {
try {
// 1.read the json file
JSONObject jsonObject = readJson();
//2.iterate json file
for (Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext(); ) {
String header = (String) iterator.next();
short type = getType(jsonObject, header);
if (type == (short) 2) {
createHeader(header);
addFieldToRow(String.valueOf(jsonObject.get(header)), header);
}
}
createExcelFile();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static void iterateJsonObject(JSONObject jsonObject, String header) {
for (Iterator outerIterate = jsonObject.keySet().iterator(); outerIterate.hasNext(); ) {
String key = (String) outerIterate.next();
short type = getType(jsonObject, key);
if (type == (short) 2) {
createHeader(header);
addFieldToRow(String.valueOf(jsonObject.get(key)), key);
}
}
}
public static void iteratorJsonArray(JSONArray jsonArray, String header) {
if (jsonArray != null) {
int index = 0;
for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) {
List<String> beforeItrFields = new ArrayList<String>();
for (String field : ((Object) row).getField()) {
beforeItrFields.add("");
}
if (index == 0) {
rowsSize = getRows().size();
}
JSONObject jsonObject = (JSONObject) iterator.next();
iterateJsonObject(jsonObject, header);
if (!getRows().contains(row)) {
getRows().add(row);
}
reInitializeObj(row);
((Object) row).setField(beforeItrFields);
index++;
} }}
public static void reInitializeObj(Object o) {
if (o instanceof Row) {
row = null;
row = new Row();
}
}
//0:jsonObject,1:jsonArray ,2:key/value
public static Short getType(JSONObject jsonObject, String key) {
if (jsonObject.get(key) instanceof JSONObject)
return (short) 0;
else if (jsonObject.get(key) instanceof JSONArray)
return (short) 1;
else
return (short) 2;
}
public static void createHeader(String key) {
if (!getHeader().contains(key))
getHeader().add(key);
}
public static void addFieldToRow(String value, String key) {
row.addField(value);
}
public static JSONObject readJson() throws IOException, ParseException {
String filePath = "C:\\Users\\skond2\\Desktop\\JSON Files\\PSEID123_APPS.json";
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
return (JSONObject) jsonParser.parse(reader);
}
public static void createExcelFile() throws IOException, IllegalAccessException, InstantiationException {
FileOutputStream fileOut = new FileOutputStream("Apps.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("work log");
HSSFRow row1 = worksheet.createRow((short) 0);
short index = 0;
//create header
for (String header : getHeader()) {
HSSFCell cellA1 = row1.createCell(index);
cellA1.setCellValue(header);
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
index++;
}
//create rows
index = 1;
for (Row row : getRows()) {
HSSFRow excelRow = worksheet.createRow(index);
short flag = 0;
for (String field : row.getField()) {
HSSFCell cellA1 = excelRow.createCell(flag);
cellA1.setCellValue(field);
flag++;
}
index++;
}
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}
}
I'm getting errors at getField, addField methods of Row interface. First thing, is it correct declaration? private static Row row =new Row();
Row is from org.apache.poi.ss.usermodel.Row;
You can use the famous Apache POI for creating excel files. It is available here with documentation links. Your question is very general. You should try to do it on your own and get back to stackoverflow when you have a precise programming question.
Your problem can be broken down into the following 3 parts
Parse the JSON
Read the required values
Write the data in excel
For the first part you can use the any of the wide range of JSON parsing APIs and can also refer to this question
For the second part, once you get the data into your code, you need to be able to read through it, for this you'd need to be able to traverse through the Object that you'll get by using the above mentioned API.
And for the last part, you can simply write the output on a file in CSV format and open it in Excel.
This answer may seem vague, please comment if you need clarification
I would like to insert values into existing work book. Here the class that encapsulates this logic:
public class FormulaExtractor {
private String pathToExcelFile;
private XSSFWorkbook workbook;
private Map<Double, Formula> idFormular = new HashMap<>();
public FormulaExtractor(String pathToExcelFile) {
this.pathToExcelFile = pathToExcelFile;
try (FileInputStream fileInputStream = new FileInputStream(new File(pathToExcelFile))) {
this.workbook = new XSSFWorkbook(fileInputStream);
} catch (FileNotFoundException e) {
System.out.println("Cannot locate a xls file. Exception: " + e.toString());
} catch (IOException e) {
System.out.println("IO exception " + e.toString());
}
}
public void insertHumanReadableFormulas() throws IOException {
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
Cell cell = currentRow.createCell(CellReference.convertColStringToIndex("K"));
cell.setCellValue("Some dummy variable to test. ");
}
FileOutputStream fileOut = new FileOutputStream(new File(this.pathToExcelFile));
workbook.write(fileOut);
fileOut.close();
}
}
How do I use it:
public class App {
public static void main(String[] args) throws IOException {
final String pathToExcel = "some/path/some_excel.xlsx";
FormulaExtractor formulaExtractor = new FormulaExtractor(pathToExcel);
formulaExtractor.insertHumanReadableFormulas();
}
}
I don't get any exception or error. When I open my excel file, I simply cannot find values in a column "K". What am I doing wrong?