Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook write

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook write

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook write.

Prototype

@SuppressWarnings("resource")
public final void write(OutputStream stream) throws IOException 

Source Link

Document

Write out this document to an Outputstream.

Usage

From source file:comparator.Comparator.java

public static void delta_MVC_MTC() throws IOException {
    //Get the input files
    //FileInputStream mtcFile = new FileInputStream(new File("\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\Catalogues\\workingMTC.xlsx"));
    //FileInputStream mvcFile = new FileInputStream(new File("\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\Catalogues\\Informal_epSOS-MVC_V1_9.xlsx"));
    FileInputStream mtcFile = new FileInputStream(new File(
            "\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\MVC2.0\\MTC_2.0.xlsx"));
    FileInputStream mtcFile2 = new FileInputStream(new File(
            "\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\MVC2.0\\MTC_2.0.xlsx"));
    FileInputStream mvcFile = new FileInputStream(new File(
            "\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\MVC2.0\\Informal_epSOS-MVC_V2_0_(DRAFT)_03.xlsx"));

    //Prepare the output file
    //Writer csvW = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\Catalogues\\delta_Mtc-Mvc.csv"), "UTF-8"));
    Writer csvW = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
            "\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\MVC2.0\\delta_Mtc-Mvc2.1.csv"),
            "UTF-8"));
    csvW.write('\ufeff');

    csvW.write("Expand Project;");
    csvW.write("\n\n");

    //Get the workbook instance for XLS file 
    XSSFWorkbook mtcWorkbook = new XSSFWorkbook(mtcFile);
    XSSFWorkbook mtcWorkbook2 = new XSSFWorkbook(mtcFile2);
    XSSFWorkbook mvcWorkbook = new XSSFWorkbook(mvcFile);

    //Output//  ww w. ja va2 s .c  om
    csvW.write("One MTC sheet is missing in MVC : VS16_epSOSErrorCodes;");
    csvW.write("\n");
    csvW.write("********************;");
    csvW.write("\n");
    csvW.write("Set name;");
    csvW.write("\n");
    csvW.write("MTC mismatches;List of the codes missing in MVC");
    csvW.write("\n");
    csvW.write("MVC mismatches;List of the codes missing in MTC");
    csvW.write("\n");
    csvW.write("********************;");

    XSSFSheet mtcSheet;
    XSSFSheet mtcSheet2;
    Iterator<Row> mtcRowIterator;
    Iterator<Row> mtcRowIterator2;
    Iterator<Row> mvcRowIterator;
    Iterator<Cell> mtcCellIterator;
    Iterator<Cell> mvcCellIterator;
    int mtcCol;
    int mvcCol;
    boolean mtcColFound;
    boolean mvcColFound;
    ArrayList mtcCodes;
    ArrayList mvcCodes;
    ArrayList mtcEnglishNames;
    ArrayList mvcEnglishNames;
    ArrayList englishNamesdifferences;
    Row mtcRow;
    Row mtcRow2;
    Row mvcRow;
    Row mvcRow2;
    Row newRow;
    Cell newCell;
    CellStyle myStyle;
    String mtcSplit[];
    String mvcSplit[];
    String mtcSheetName;
    String mvcSheetName;

    //Get the sheet from the MTC workbook
    for (int i = 0; i < mtcWorkbook.getNumberOfSheets(); i++) {
        mtcSheet = mtcWorkbook.getSheetAt(i);
        mtcSheet2 = mtcWorkbook2.getSheetAt(i);

        //Get iterator to all the rows in current MTC sheet
        mtcRowIterator = mtcSheet.iterator();
        mtcRowIterator2 = mtcSheet2.iterator();

        //Get the sheet from the MVC workbook
        for (int j = 0; j < mvcWorkbook.getNumberOfSheets(); j++) {
            XSSFSheet mvcSheet = mvcWorkbook.getSheetAt(j);

            //Get iterator to all the rows in current MVC sheet
            mvcRowIterator = mvcSheet.iterator();

            //Get the name of MTC sheet and MVC sheet, compare them if they contain data
            //MTC data files are called "VSX_sheetName"
            //MVC data files are called "epSOSsheetName"
            mtcSplit = mtcSheet.getSheetName().split("_");
            mvcSplit = mvcSheet.getSheetName().split("SOS");
            mtcSheetName = mtcSplit[mtcSplit.length - 1];
            mvcSheetName = mvcSplit[mvcSplit.length - 1];

            //And process the file matching or throw out the file that has no equivalent
            if (mtcSheetName.equals(mvcSheetName)) {

                mtcCol = 0;
                mvcCol = 0;
                mtcColFound = false;
                mvcColFound = false;
                mtcCodes = new ArrayList();
                mvcCodes = new ArrayList();
                mtcEnglishNames = new ArrayList();
                mvcEnglishNames = new ArrayList();
                englishNamesdifferences = new ArrayList();

                //For each row, iterate through each columns
                //Get iterator to all cells of current row
                //In MTC
                while (mtcRowIterator.hasNext()) {
                    mtcRow = mtcRowIterator.next();
                    mtcRow2 = mtcRow;

                    if (mtcColFound == false) {
                        mtcCellIterator = mtcRow.cellIterator();

                        while (mtcCellIterator.hasNext()) {
                            Cell mtcCell = mtcCellIterator.next();
                            if (mtcCell.getCellType() == 1 && (mtcCell.getStringCellValue().equals("Code")
                                    || mtcCell.getStringCellValue().equals("epSOS Code"))) {
                                mtcCol = mtcCell.getColumnIndex();
                                mtcColFound = true;
                                break;
                            }
                        }
                    } else {
                        mtcRow.getCell(mtcCol, Row.CREATE_NULL_AS_BLANK).setCellType(Cell.CELL_TYPE_STRING);
                        mtcRow2.getCell(mtcCol + 1, Row.CREATE_NULL_AS_BLANK)
                                .setCellType(Cell.CELL_TYPE_STRING);
                        mtcCodes.add(mtcRow.getCell(mtcCol).getStringCellValue().trim());
                        mtcEnglishNames.add(mtcRow2.getCell(mtcCol + 1).getStringCellValue().trim());
                    }
                }

                //In MVC
                while (mvcRowIterator.hasNext()) {
                    mvcRow = mvcRowIterator.next();
                    mvcRow2 = mvcRow;
                    if (mvcColFound == false) {
                        mvcCellIterator = mvcRow.cellIterator();

                        while (mvcCellIterator.hasNext()) {
                            Cell mvcCell = mvcCellIterator.next();

                            if (mvcCell.getCellType() == 1 && (mvcCell.getStringCellValue().equals("epSOS Code")
                                    || mvcCell.getStringCellValue().equals("Code"))) {
                                mvcCol = mvcCell.getColumnIndex();
                                mvcColFound = true;
                                break;
                            }
                        }
                    } else {
                        mvcRow.getCell(mvcCol, Row.CREATE_NULL_AS_BLANK).setCellType(Cell.CELL_TYPE_STRING);
                        mvcRow2.getCell(mvcCol + 1, Row.CREATE_NULL_AS_BLANK)
                                .setCellType(Cell.CELL_TYPE_STRING);
                        mvcCodes.add(mvcRow.getCell(mvcCol).getStringCellValue().trim());
                        mvcEnglishNames.add(mvcRow2.getCell(mvcCol + 1).getStringCellValue().trim());
                    }
                }

                //Processing
                colCompare(mtcCodes, mvcCodes, mvcEnglishNames, mtcEnglishNames, englishNamesdifferences);

                //Output
                //if((!mtcCodes.isEmpty()) || (!mvcCodes.isEmpty())) {}
                csvW.write("\n\n");
                csvW.write(mtcSheetName + ";");
                csvW.write("\n");
                csvW.write("MTC mismatches;");
                for (int a = 0; a < mtcCodes.size(); a++) {
                    csvW.write(mtcCodes.get(a) + ";");
                }
                csvW.write("\n");
                csvW.write("MVC mismatches\n");
                for (int b = 0; b < mvcCodes.size(); b++) {
                    csvW.write(mvcCodes.get(b) + ";" + mvcEnglishNames.get(b) + "\n");
                }

                csvW.write("english names differences\n");
                if (!englishNamesdifferences.isEmpty()) {
                    csvW.write("code;MTC 2.0;MVC 2.0.1\n");
                    for (int c = 0; c < englishNamesdifferences.size(); c = c + 3) {
                        csvW.write(englishNamesdifferences.get(c) + ";" + englishNamesdifferences.get(c + 1)
                                + ";" + englishNamesdifferences.get(c + 2) + "\n");
                    }
                }

                /* work on currents MTC2.0 sheet */
                mtcColFound = false;
                mtcCol = 0;
                List<Integer> delRows = new ArrayList();

                //recreate iterator to all the rows in current MTC sheet
                while (mtcRowIterator2.hasNext()) {
                    mtcRow = mtcRowIterator2.next();
                    mtcRow2 = mtcRow;
                    if (mtcColFound == false) {
                        mtcCellIterator = mtcRow.cellIterator();

                        while (mtcCellIterator.hasNext()) {
                            Cell mtcCell = mtcCellIterator.next();
                            if (mtcCell.getCellType() == 1 && (mtcCell.getStringCellValue().equals("Code")
                                    || mtcCell.getStringCellValue().equals("epSOS Code"))) {
                                mtcCol = mtcCell.getColumnIndex();
                                mtcColFound = true;
                                break;
                            }
                        }
                    } else {
                        mtcRow.getCell(mtcCol, Row.RETURN_NULL_AND_BLANK).setCellType(Cell.CELL_TYPE_STRING);
                        mtcRow2.getCell(mvcCol + 1, Row.CREATE_NULL_AS_BLANK)
                                .setCellType(Cell.CELL_TYPE_STRING);

                        for (int a = 0; a < mtcCodes.size(); a++) {
                            if (mtcRow.getCell(mtcCol).getStringCellValue().trim().equals(mtcCodes.get(a))) {
                                // delete row corresponding to useless code
                                delRows.add(mtcRow.getRowNum());
                                break;
                            }
                        }

                        if (!englishNamesdifferences.isEmpty()) {
                            for (int c = 0; c < englishNamesdifferences.size(); c = c + 3) {
                                if (mtcRow2.getCell(mtcCol + 1).getStringCellValue().trim()
                                        .equals(englishNamesdifferences.get(c + 1))) {
                                    mtcRow2.getCell(mtcCol + 1)
                                            .setCellValue(englishNamesdifferences.get(c + 2).toString());
                                    break;
                                }
                            }
                        }
                    }
                }
                for (int d = delRows.size() - 1; d >= 0; d--) {
                    mtcSheet2.shiftRows(delRows.get(d) + 1, mtcSheet2.getLastRowNum() + 1, -1);
                }
                myStyle = mtcSheet2.getRow(0).getCell(0).getCellStyle();
                for (int b = 0; b < mvcCodes.size(); b++) {
                    newRow = mtcSheet2.createRow(mtcSheet2.getLastRowNum() + 1);
                    for (int bb = 0; bb < mtcSheet2.getRow(0).getLastCellNum(); bb++) {
                        newCell = newRow.createCell(bb);
                        newCell.setCellStyle(myStyle);
                        if (bb == mtcCol) {
                            newCell.setCellValue(mvcCodes.get(b).toString());
                        } else if (bb == mtcCol + 1) {
                            newCell.setCellValue(mvcEnglishNames.get(b).toString());
                        }
                    }
                }
            }
        }
    }
    //close InputStream
    mtcFile.close();
    mtcFile2.close();
    mvcFile.close();
    //close OutputStream
    csvW.close();

    //Open FileOutputStream to write updates
    FileOutputStream output_file = new FileOutputStream(new File(
            "\\\\hes-nas-drize.hes.adhes.hesge.ch\\home\\luc.mottin\\Documents\\Expand\\MVC2.0\\MTC_2.0_new.xlsx"));
    //write changes
    mtcWorkbook2.write(output_file);
    //close the stream
    output_file.close();
}

From source file:controller.application.employee.ViewEmployeController.java

private void toExcel(ArrayList<ToExcelEmployee> lst, ArrayList<RFIDTimestamp> times, File file, Timestamp from,
        Timestamp to) throws IOException {

    try {//  w  w w . j a  va  2s .co  m
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet spreadsheet = workbook.createSheet("Total arbetad tid " + file.getName());
        XSSFRow row = spreadsheet.createRow(0);
        XSSFCell cell;
        cell = row.createCell(0);
        cell.setCellValue("Frnamn:");
        cell = row.createCell(1);
        cell.setCellValue("Efternamn:");
        cell = row.createCell(2);
        cell.setCellValue("Anstllningsnummer:");
        cell = row.createCell(3);
        cell.setCellValue("Individuell tid (h) from.: " + (from.toString() + " tom.: " + to.toString())
                .replaceAll("(\\s)((\\p{Digit}{2}:){2}\\p{Digit}{2})\\..", ""));
        Double totAllTime = 0.0;
        for (int i = 1; i <= lst.size(); i++) {
            row = spreadsheet.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(lst.get(i - 1).surname);
            cell = row.createCell(1);
            cell.setCellValue(lst.get(i - 1).lastname);
            cell = row.createCell(2);
            cell.setCellValue(lst.get(i - 1).id);
            cell = row.createCell(3);
            cell.setCellValue(lst.get(i - 1).time);
            totAllTime += lst.get(i - 1).time;
            if (i == lst.size()) {
                row = spreadsheet.createRow(i + 1);
                cell = row.createCell(3);
                cell.setCellValue("Sammanstllning:");
                row = spreadsheet.createRow(i + 2);
                cell = row.createCell(3);
                cell.setCellValue(totAllTime);
            }

        }

        XSSFSheet spreadsheetTimes = workbook.createSheet("Tider");
        row = spreadsheetTimes.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("RFID");
        cell = row.createCell(1);
        cell.setCellValue("IN/UT");
        cell = row.createCell(2);
        cell.setCellValue("Datum/Tid");

        for (int i = 1; i <= times.size(); i++) {
            row = spreadsheetTimes.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(times.get(i - 1).getRFID().toString());
            cell = row.createCell(1);
            cell.setCellValue(times.get(i - 1).getInOut());
            cell = row.createCell(2);
            cell.setCellValue(times.get(i - 1).getTime());
        }
        for (int k = 0; k < spreadsheet.getRow(0).getLastCellNum(); k++) {
            spreadsheet.autoSizeColumn(k);
        }
        for (int j = 0; j < spreadsheetTimes.getRow(0).getLastCellNum(); j++) {
            spreadsheetTimes.autoSizeColumn(j);
        }

        try (FileOutputStream out = new FileOutputStream(file)) {
            workbook.write(out);
        }
        System.out.println(file.getName() + " written successfully");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:controller.DAORequest.java

public void saveResolution() {
    XSSFWorkbook reqWB = new XSSFWorkbook();
    XSSFSheet sheet = reqWB.createSheet();
    Row rowZ = sheet.createRow(0);//  w  w  w . j  a  va  2s .com
    sheet.getRow(0).createCell(0).setCellValue("Id");
    sheet.getRow(0).createCell(1).setCellValue("Attention");
    sheet.getRow(0).createCell(2).setCellValue("Title");
    sheet.getRow(0).createCell(3).setCellValue("Intro");
    sheet.getRow(0).createCell(4).setCellValue("Result");
    sheet.getRow(0).createCell(5).setCellValue("Resolve");
    sheet.getRow(0).createCell(6).setCellValue("Notify");
    sheet.getRow(0).createCell(7).setCellValue("Considerations");
    ArrayList<Resolution> resolutions = new ArrayList<>();
    for (Object o : School.getInstance().selectAllRequests()) {
        Request r = (Request) o;
        if (r.getResolution() != null) {
            resolutions.add(r.getResolution());

        }
    }

    int rowI = 1;
    for (Resolution r : resolutions) {
        Row row = sheet.createRow(rowI);
        //
        Cell cellId = row.createCell(0);
        cellId.setCellValue(r.getId());
        Cell cellAttention = row.createCell(1);
        cellAttention.setCellValue(r.getAttention());
        Cell cellTitle = row.createCell(2);
        cellTitle.setCellValue(r.getTitle());
        Cell cellIntro = row.createCell(3);
        cellIntro.setCellValue(r.getIntro());
        Cell cellResult = row.createCell(4);
        cellResult.setCellValue(r.getResult());
        Cell cellResolve = row.createCell(5);
        cellResolve.setCellValue(r.getResolve());
        Cell cellNotify = row.createCell(6);
        cellNotify.setCellValue(r.getNotify());
        Cell cellCons = row.createCell(7);
        cellCons.setCellValue(r.getConsider());
        rowI++;

    }

    // Save to excel file 
    try {

        FileOutputStream out = new FileOutputStream(new File("src//files//DatosResolucion.xlsx"));

        reqWB.write(out);

        reqWB.close();
        out.close();

    } catch (FileNotFoundException ex) {

        Logger.getLogger(DAORequest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {

        Logger.getLogger(DAORequest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:controller.ExcelConsultant.java

static void logResult(ArrayList<Result> result, File outputFile, String name) {

    try {// www . j  a  va2 s. co  m

        FileInputStream fis;
        fis = new FileInputStream(outputFile);
        XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);
        XSSFSheet sheet = myWorkBook.getSheetAt(0);

        int nRow = sheet.getPhysicalNumberOfRows();

        if (nRow == 0) {
            sheet.createRow(nRow);

            sheet.getRow(nRow).createCell(0).setCellValue("Timestamp");
            sheet.getRow(nRow).createCell(1).setCellValue("Name");
            sheet.getRow(nRow).createCell(2).setCellValue("Trade Name");
            sheet.getRow(nRow).createCell(3).setCellValue("Number");
            sheet.getRow(nRow).createCell(4).setCellValue("Person");
            sheet.getRow(nRow).createCell(5).setCellValue("Notes");

            nRow++;
        }

        for (Result res : result) {

            sheet.createRow(nRow);

            Date date = new Date();
            sheet.getRow(nRow).createCell(0).setCellValue(date.toString());
            sheet.getRow(nRow).createCell(1).setCellValue(name);
            sheet.getRow(nRow).createCell(2).setCellValue(res.getTradeName());
            sheet.getRow(nRow).createCell(3).setCellValue(res.getNumber());
            sheet.getRow(nRow).createCell(4).setCellValue(res.getPerson());
            sheet.getRow(nRow).createCell(5).setCellValue(res.getNotes());

            nRow++;
        }
        //important to close InputStream
        fis.close();
        //Open FileOutputStream to write updates
        FileOutputStream output_file = new FileOutputStream(outputFile);
        //write changes
        myWorkBook.write(output_file);
        //close the stream
        output_file.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:courtscheduler.persistence.CourtScheduleIO.java

License:Apache License

public String writeXlsx(List<Match> matches, CourtScheduleInfo info, String filepath) throws IOException {

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet;//from  w w  w .  jav  a2  s.  com
    sheet = null;
    rowNumber = 0;
    int cellNumber = 0;
    String lastConf = "";

    // print out master schedule
    Collections.sort(matches, Match.timeComparator);
    sheet = initializePage(workbook, "Master");
    for (Match match : matches) {
        rowNumber++;
        printMatch(sheet.createRow(rowNumber), match, info);
    }

    // print out individual conferences
    rowNumber = 0;
    Collections.sort(matches, Match.conferenceComparator);

    for (Match match : matches) {
        if (!match.getConference().equals(lastConf)) {
            sheet = initializePage(workbook, match.getConference());
        }

        rowNumber++;
        printMatch(sheet.createRow(rowNumber), match, info);
        lastConf = match.getConference();
    }

    Scanner input = new Scanner(System.in);
    String reply = "";
    boolean continueInput = true;
    StackTraceElement[] stackTraceE = new StackTraceElement[100];
    do {
        try {
            FileOutputStream out = new FileOutputStream(new File(filepath));
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully to " + filepath + ".");
            continueInput = false;

        } catch (FileNotFoundException e) {
            stackTraceE = e.getStackTrace();
            System.out.println("An output file already exists and is open.");
            System.out.println("To overwrite: close it, then hit 'enter'.");
            System.out.println("To create a new output file: enter new name or path.");
            System.out.println("To quit: type 'q'.");
            reply = input.nextLine();
            if (reply.regionMatches(true, 0, "q", 0, 1))
                return null;
            else if (reply.equals(""))
                continue;
            else
                filepath = reply;

        } catch (IOException e) {
            stackTraceE = e.getStackTrace();
            System.out.println(
                    "Output error.  Please enter new name or path for this output file, or 'q' to quit: ");
            reply = input.nextLine();
            if (reply.regionMatches(true, 0, "q", 0, 1))
                return null;
            else
                filepath = reply;
        }
    } while (continueInput);
    return filepath;
}

From source file:cv_extractor.DocReader.java

protected static void generateExcel(String directory, String fileName) {
    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Email Address");

    //Create CellStyle for header (First row)
    CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
    Font font = sheet.getWorkbook().createFont();
    font.setBold(true);//ww w .j a va 2  s .  c o  m
    font.setFontHeightInPoints((short) 16);
    cellStyle.setFont(font);

    //Create first row (Header)
    Row header = sheet.createRow(0);

    //Creating a cell (Only one required, for single attribute E-mail)
    Cell cellTitle = header.createCell(1);
    cellTitle.setCellStyle(cellStyle);
    cellTitle.setCellValue("E-Mail");

    //Counter to use while creating further rows, starting from row 1
    int rowNum = 1;

    //Iterate over data and write to sheet   
    Iterator<String> iterator = data.iterator();

    while (iterator.hasNext()) {
        //Create a row for each E-mail string
        Row row = sheet.createRow(rowNum++);

        //Create a cell to put the E-mail string
        Cell cell = row.createCell(1);

        //Put value in the cell
        cell.setCellValue(iterator.next());
    }

    try {
        //Write the workbook in file system

        if (fileName.equals("")) {
            fileName = "Email List";
        }

        FileOutputStream out = new FileOutputStream(new File(directory + "/" + fileName + ".xlsx"));
        workbook.write(out);
        out.close();

        JOptionPane.showMessageDialog(null, "File generated !");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cz.lbenda.dataman.db.ExportTableData.java

License:Apache License

/** Write rows to XLSX file
 * @param sqlQueryRows rows// ww w .  j a v a  2s  .  com
 * @param sheetName name of sheet where is data write
 * @param outputStream stream where are data write */
public static void writeSqlQueryRowsToXLSX(SQLQueryRows sqlQueryRows, String sheetName,
        OutputStream outputStream) throws IOException {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet(sheetName);
    XSSFRow headerRow = sheet.createRow(0);
    int c = 0;
    for (ColumnDesc columnDesc : sqlQueryRows.getMetaData().getColumns()) {
        XSSFCell cell = headerRow.createCell(c);
        cell.setCellValue(columnDesc.getName());
        c++;
    }
    int r = 1;
    for (RowDesc row : sqlQueryRows.getRows()) {
        XSSFRow xlsxRow = sheet.createRow(r);
        c = 0;
        for (ColumnDesc columnDesc : sqlQueryRows.getMetaData().getColumns()) {
            XSSFCell cell = xlsxRow.createCell(c);
            cell.setCellValue(row.getColumnValueStr(columnDesc));
            c++;
        }
        r++;
    }
    wb.write(outputStream);
}

From source file:Dao.XlsBillDao.java

public void GenFullXLS(String pono, String relpath) {
    try {//from   www. j a  va2  s. c o  m
        //0.Declare Variables for Sheet
        //DB Variable
        //            pono = "WO/2015/2005";
        //XLS Variable
        XSSFSheet spreadsheet;
        XSSFWorkbook workbook;
        XSSFRow row;
        XSSFCell cell;
        XSSFFont xfont = null;
        XSSFCellStyle xstyle = null;

        //1.Get Connection and Fetch Data
        ArrayList<WorkItemBean> wi1 = new ArrayList<WorkItemBean>();
        WorkDao wdao1 = new WorkDao();
        wi1 = wdao1.getWOItem(pono);

        //2.Create WorkBook and Sheet
        workbook = new XSSFWorkbook();
        spreadsheet = workbook.createSheet("WorkOrder Detail");

        //   spreadsheet.protectSheet("kandarpCBA");
        //        spreadsheet.setColumnWidth(0, 255);
        //set header style
        xfont = workbook.createFont();
        xfont.setFontHeight(11);
        xfont.setFontName("Calibri");
        xfont.setBold(true);
        //Set font into style

        CellStyle borderStyle = workbook.createCellStyle();
        borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
        borderStyle.setFont(xfont);

        xstyle = workbook.createCellStyle();
        xstyle.setFont(xfont);

        //header
        row = spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("WORK ORDER NO : " + pono);
        cell.setCellStyle(borderStyle);
        spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

        //3.Get First Row and Set Headers
        row = spreadsheet.createRow(1);
        cell = row.createCell(0);
        cell.setCellValue("LINE_NO");
        cell.setCellStyle(xstyle);
        cell = row.createCell(1);
        cell.setCellValue("ITEM_ID");
        cell.setCellStyle(xstyle);
        cell = row.createCell(2);
        cell.setCellValue("DESCRIPTION");
        cell.setCellStyle(xstyle);
        cell = row.createCell(3);
        cell.setCellValue("UOM");
        cell.setCellStyle(xstyle);
        cell = row.createCell(4);
        cell.setCellValue("QTY");
        cell.setCellStyle(xstyle);
        cell = row.createCell(5);
        cell.setCellValue("RATE");
        cell.setCellStyle(xstyle);
        cell = row.createCell(6);
        cell.setCellValue("NOTE");
        cell.setCellStyle(xstyle);

        int i = 2;
        for (WorkItemBean w : wi1) {
            row = spreadsheet.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(w.getLINE_NO());
            cell = row.createCell(1);
            cell.setCellValue(w.getITEM_ID());
            cell = row.createCell(2);
            cell.setCellValue(w.getITEM_DESC());
            cell = row.createCell(3);
            cell.setCellValue(w.getUOM());
            cell = row.createCell(4);
            cell.setCellValue(w.getQTY());
            cell = row.createCell(5);
            cell.setCellValue(w.getRATE());
            cell = row.createCell(6);
            cell.setCellValue(w.getCMT());
            i++;
        }

        //Export to Excel
        //            FileOutputStream out = new FileOutputStream(new File("D://" + pono.replace("/", "-") + "_Items" + ".xlsx"));
        FileOutputStream out = new FileOutputStream(
                new File(relpath + "uxls//" + pono.replace("/", "-") + "_Items" + ".xlsx"));
        workbook.write(out);
        out.close();
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "DONE|!");
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "{0}uxls//{1}" + "_Items" + ".xlsx",
                new Object[] { relpath, pono.replace("/", "-") });
    } catch (FileNotFoundException ex) {
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    } catch (IOException ex) {
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    }
}

From source file:Dao.XlsBillDao.java

public void GenXLS(String pono, String relpath) {
    try {/*from w ww . j  a  va2 s.c  o  m*/
        //0.Declare Variables for Sheet
        //DB Variable
        //            pono = "WO/2015/2005";
        String sql;
        Connection con;
        PreparedStatement ps;
        ResultSet rs;
        //XLS Variable
        XSSFSheet spreadsheet;
        XSSFWorkbook workbook;
        XSSFRow row;
        XSSFCell cell;
        XSSFFont xfont = null;
        XSSFCellStyle xstyle = null;

        //1.Get Connection and Fetch Data
        con = DBmanager.GetConnection();
        sql = "SELECT DISTINCT cba_wo_item.line_no, cba_wo_item.item_id,\n"
                + "                mtl_system_items.description, cba_wo_item.uom,\n"
                + "                cba_wo_item.qty, cba_wo_item.rate, cba_wo_item.cmt,\n"
                + "                cba_wo_item.plant, cba_wo_item.proj, cba_wo_item.task,"
                + "                cba_wo_item.po_no\n" + "           FROM cba_wo_item, mtl_system_items\n"
                + "          WHERE (    (cba_wo_item.item_id = mtl_system_items.segment1)\n"
                + "                 AND (mtl_system_items.organization_id = 0)\n"
                + "                 AND (cba_wo_item.po_no = '" + pono + "')\n" + "                )\n"
                + "       ORDER BY cba_wo_item.line_no";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();

        //2.Create WorkBook and Sheet
        workbook = new XSSFWorkbook();
        spreadsheet = workbook.createSheet("WorkOrder Detail");

        //spreadsheet.protectSheet("kandarpCBA");
        //spreadsheet.setColumnWidth(0, 255);
        //set header style
        xfont = workbook.createFont();
        xfont.setFontHeight(11);
        xfont.setFontName("Calibri");
        xfont.setBold(true);
        //Set font into style
        CellStyle borderStyle = workbook.createCellStyle();
        borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
        borderStyle.setFont(xfont);
        //        borderStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
        //        borderStyle.setFillPattern(CellStyle.ALIGN_FILL);

        xstyle = workbook.createCellStyle();
        xstyle.setFont(xfont);

        //header
        row = spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("WORK ORDER NO : " + pono
                + " Note : If WO is with project information,each bill item should have project and task");
        cell.setCellStyle(borderStyle);
        spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));

        //3.Get First Row and Set Headers
        row = spreadsheet.createRow(1);
        cell = row.createCell(0);
        cell.setCellValue("LINE_NO");
        cell.setCellStyle(xstyle);
        cell = row.createCell(1);
        cell.setCellValue("ITEM_ID");
        cell.setCellStyle(xstyle);
        cell = row.createCell(2);
        cell.setCellValue("DESCRIPTION");
        cell.setCellStyle(xstyle);
        cell = row.createCell(3);
        cell.setCellValue("UOM");
        cell.setCellStyle(xstyle);
        cell = row.createCell(4);
        cell.setCellValue("QTY");
        cell.setCellStyle(xstyle);
        cell = row.createCell(5);
        cell.setCellValue("RATE");
        cell.setCellStyle(xstyle);
        cell = row.createCell(6);
        cell.setCellValue("WO NOTE");
        cell.setCellStyle(xstyle);
        cell = row.createCell(7);
        cell.setCellValue("PLANT");
        cell.setCellStyle(xstyle);
        cell = row.createCell(8);
        cell.setCellValue("COST CENTER");
        cell.setCellStyle(xstyle);
        cell = row.createCell(9);
        cell.setCellValue("PROJECT");
        cell.setCellStyle(xstyle);
        cell = row.createCell(10);
        cell.setCellValue("TASK");
        cell.setCellStyle(xstyle);
        cell = row.createCell(11);
        cell.setCellValue("HERE ADD NOTE");
        cell.setCellStyle(xstyle);

        //Itrate or Database data and write
        int i = 2;
        while (rs.next()) {
            row = spreadsheet.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(rs.getString(1));
            cell = row.createCell(1);
            cell.setCellValue(rs.getString(2));
            cell = row.createCell(2);
            cell.setCellValue(rs.getString(3));
            cell = row.createCell(3);
            cell.setCellValue(rs.getString(4));
            cell = row.createCell(4);
            cell.setCellValue(rs.getString(6));
            cell = row.createCell(5);
            cell.setCellValue(rs.getString(5));
            cell = row.createCell(6);
            cell.setCellValue("");
            cell = row.createCell(7);
            cell.setCellValue(rs.getString(7));
            cell = row.createCell(8);
            cell.setCellValue(rs.getString(8));
            cell = row.createCell(9);
            cell.setCellValue(rs.getString(9));
            cell = row.createCell(10);
            cell.setCellValue(rs.getString(10));
            cell = row.createCell(11);
            cell.setCellValue("");
            i++;
        }

        //SECOND WORKSHEET FOR COST CENTER AND PLANT DETAIL
        XSSFRow row2;
        XSSFCell cell2;
        XSSFSheet ccsheet = workbook.createSheet("Cost Center");
        row2 = ccsheet.createRow(0);
        cell2 = row2.createCell(0);
        cell2.setCellValue("Cost Center name and code. Please enter only code in excel");
        cell2.setCellStyle(borderStyle);
        ccsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));

        row2 = ccsheet.createRow(1);
        cell2 = row2.createCell(0);
        cell2.setCellValue("CODE");
        cell2.setCellStyle(xstyle);

        cell2 = row2.createCell(1);
        cell2.setCellValue("NAME");
        cell2.setCellStyle(xstyle);

        con = DBmanager.GetConnection();
        sql = "select cc,plant from cba_cc_mst";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        int i2 = 2;
        while (rs.next()) {
            row2 = ccsheet.createRow(i2);
            cell2 = row2.createCell(0);
            cell2.setCellValue(rs.getString(1));
            cell2 = row2.createCell(1);
            cell2.setCellValue(rs.getString(2));
            i2++;
        }

        //THIRD SHEET
        //SECOND WORKSHEET FOR COST CENTER AND PLANT DETAIL
        XSSFRow row3;
        XSSFCell cell3;
        XSSFSheet plantsheet = workbook.createSheet("Plant Center");
        row3 = plantsheet.createRow(0);
        cell3 = row3.createCell(0);
        cell3.setCellValue("Plant Center name and code. Please enter only code in excel");
        cell3.setCellStyle(borderStyle);
        plantsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));

        row3 = plantsheet.createRow(1);
        cell3 = row3.createCell(0);
        cell3.setCellValue("CODE");
        cell3.setCellStyle(xstyle);

        cell3 = row3.createCell(1);
        cell3.setCellValue("NAME");
        cell3.setCellStyle(xstyle);

        con = DBmanager.GetConnection();
        sql = "select cc,plant from cba_plant_mst";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        int i3 = 2;
        while (rs.next()) {
            row3 = plantsheet.createRow(i3);
            cell3 = row3.createCell(0);
            cell3.setCellValue(rs.getString(1));
            cell3 = row3.createCell(1);
            cell3.setCellValue(rs.getString(2));
            i3++;
        }
        //SHEET 3 HEADER
        //row1
        XSSFSheet spreadsheet4 = workbook.createSheet("Project And Task");
        XSSFRow row4 = spreadsheet4.createRow(0);
        XSSFCell cell4 = row4.createCell(0);
        cell4.setCellValue("Note : Please copy project,task code and paste into 1 sheet");
        spreadsheet4.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        //row2  
        row4 = spreadsheet4.createRow(1);
        cell4 = row4.createCell(0);
        cell4.setCellValue("PROJECT CODE");
        cell4.setCellStyle(xstyle);
        cell4 = row4.createCell(1);
        cell4.setCellValue("PROJECT NAME");
        cell4.setCellStyle(xstyle);
        cell4 = row4.createCell(2);
        cell4.setCellValue("TASK CODE");
        cell4.setCellStyle(xstyle);
        //SHEET 3 DATA
        int j = 2;
        ArrayList<WorkItemBean> wi1 = Dropdown.LoadProjTaskMst("123");
        for (WorkItemBean w : wi1) {
            row4 = spreadsheet4.createRow(j);
            cell4 = row4.createCell(0);
            cell4.setCellValue(w.getPROJ());
            cell4 = row4.createCell(1);
            cell4.setCellValue(w.getPROJ_NAME());
            cell4 = row4.createCell(2);
            cell4.setCellValue(w.getTASK());
            j++;
        }

        //Export to Excel
        //            FileOutputStream out = new FileOutputStream(new File("D://" + pono.replace("/", "-") + ".xlsx"));
        FileOutputStream out = new FileOutputStream(
                new File(relpath + "xls//" + pono.replace("/", "-") + ".xlsx"));
        workbook.write(out);
        out.close();

        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "DONE|!");
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "{0}xls//{1}.xlsx",
                new Object[] { relpath, pono.replace("/", "-") });
    } catch (SQLException ex) {
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    } catch (IOException ex) {
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    }
}

From source file:Dao.XlsWoDao.java

public void GenXLS(String orgId, String relpath) {
    try {/*from  w w  w .j  ava 2s.  co m*/
        //2.Create WorkBook and Sheet
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet spreadsheet1 = workbook.createSheet("WorkOrder Detail");
        XSSFSheet spreadsheet2 = workbook.createSheet("Plant Master");
        XSSFSheet spreadsheet3 = workbook.createSheet("Project and Task Master");
        //style
        XSSFFont xfont = workbook.createFont();
        xfont.setFontHeight(11);
        xfont.setFontName("Calibri");
        xfont.setBold(true);
        //Set font into style
        CellStyle borderStyle = workbook.createCellStyle();
        borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
        borderStyle.setFont(xfont);
        XSSFCellStyle xstyle = workbook.createCellStyle();
        xstyle.setFont(xfont);

        //SHEET 1 HEADER
        //1row
        XSSFRow row1 = spreadsheet1.createRow(0);
        XSSFCell cell1 = row1.createCell(0);
        cell1.setCellValue("Note : If you are not sure " + "about plant,project,task please "
                + "leave it blank." + "It can be add when release bill");
        spreadsheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 15));
        //2row
        row1 = spreadsheet1.createRow(1);
        cell1 = row1.createCell(0);
        cell1.setCellValue("Create Work Order Template");
        cell1.setCellStyle(borderStyle);
        spreadsheet1.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
        //3row
        row1 = spreadsheet1.createRow(2);
        cell1 = row1.createCell(0);
        cell1.setCellValue("ITEM_NO");
        cell1.setCellStyle(xstyle);
        cell1 = row1.createCell(1);
        cell1.setCellValue("RATE");
        cell1.setCellStyle(xstyle);
        cell1 = row1.createCell(2);
        cell1.setCellValue("PLANT");
        cell1.setCellStyle(xstyle);
        cell1 = row1.createCell(3);
        cell1.setCellValue("PROJECT");
        cell1.setCellStyle(xstyle);
        cell1 = row1.createCell(4);
        cell1.setCellValue("TASK");
        cell1.setCellStyle(xstyle);
        cell1 = row1.createCell(5);
        cell1.setCellValue("ADDITIONAL NOTE");
        cell1.setCellStyle(xstyle);

        //SHEET 2 HEADER
        //row1
        XSSFRow row2 = spreadsheet2.createRow(0);
        XSSFCell cell2 = row2.createCell(0);
        cell2.setCellValue("Note : Please copy plant code and paste into 1 sheet");
        spreadsheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        //row2  
        row2 = spreadsheet2.createRow(1);
        cell2 = row2.createCell(0);
        cell2.setCellValue("PLANT_CODE");
        cell2.setCellStyle(xstyle);
        cell2 = row2.createCell(1);
        cell2.setCellValue("PLANT NAME");
        cell2.setCellStyle(xstyle);
        //SHEET 2 DATA
        int i = 2;
        Map<String, String> plant = Dropdown.LoadPlantMst();
        for (Map.Entry<String, String> entry : plant.entrySet()) {
            row2 = spreadsheet2.createRow(i);
            cell2 = row2.createCell(0);
            cell2.setCellValue(entry.getKey());
            cell2 = row2.createCell(1);
            cell2.setCellValue(entry.getValue());
            i++;
        }

        //SHEET 3 HEADER
        //row1
        XSSFRow row3 = spreadsheet3.createRow(0);
        XSSFCell cell3 = row3.createCell(0);
        cell3.setCellValue("Note : Please copy project,task code and paste into 1 sheet");
        spreadsheet3.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
        //row2  
        row3 = spreadsheet3.createRow(1);
        cell3 = row3.createCell(0);
        cell3.setCellValue("PROJECT CODE");
        cell3.setCellStyle(xstyle);
        cell3 = row3.createCell(1);
        cell3.setCellValue("PROJECT NAME");
        cell3.setCellStyle(xstyle);
        cell3 = row3.createCell(2);
        cell3.setCellValue("TASK CODE");
        cell3.setCellStyle(xstyle);
        //SHEET 3 DATA
        int j = 2;
        ArrayList<WorkItemBean> wi1 = Dropdown.LoadProjTaskMst(orgId);
        for (WorkItemBean w : wi1) {
            row3 = spreadsheet3.createRow(j);
            cell3 = row3.createCell(0);
            cell3.setCellValue(w.getPROJ());
            cell3 = row3.createCell(1);
            cell3.setCellValue(w.getPROJ_NAME());
            cell3 = row3.createCell(2);
            cell3.setCellValue(w.getTASK());
            j++;
        }
        //Export to Excel
        // FileOutputStream out = new FileOutputStream(new File("D://" + pono.replace("/", "-") + "_Items" + ".xlsx"));
        //   FileOutputStream out = new FileOutputStream(new File(relpath + "uxls//" + "WO_Creation_Template" + ".xlsx"));
        FileOutputStream out = new FileOutputStream(new File(relpath));
        workbook.write(out);
        out.close();
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "DONE|!");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    } catch (IOException ex) {
        Logger.getLogger(XlsBillDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    }
}