Asked  1 Year ago    Answers:  5   Viewed   12 times

I have written an Export script that will export data from my database as a CSV or XLS file. The data from the database needs to be manipulated first. So far I have the CSV file working and am now trying to convert this CSV string to XLS. I want to use phpExcel but get the below error. Can anyone assist?

Fatal error:  Class 'PHPExcel_Exception' not found in /var/www/leanne/api/library/PHPExcel/Exception.php on line 36

Code which is causing the error, all worked fine until I added the XLS stuff:

if($format == 'csv'){  
                //create and write to file for CSV
                if(file_exists($file_location . $filename)){
                    unlink($file_location . $filename);
                }
                $fh = fopen($file_location . $filename , 'a');
                fwrite($fh, $csv);
                fclose($fh);
            } else if($format == 'xls'){ 
                //wite to file for XLS
                include '../library/PHPExcel/IOFactory.php';

                $objReader = PHPExcel_IOFactory::createReader('CSV');
                $objReader->setDelimiter($separator); 
                $objReader->setEnclosure(" ");
                $objReader->setLineEnding($endrow);

                $objPHPExcel = $objReader->load($csv);
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                $objWriter->save($file_location . $filename);               

            }

NB: csv is a string containing comma separated and double quoted fields from the database. The lines end with 'n'.

 Answers

1

Ive downloaded the files again and started from scratch and its working. Must have been something silly I had done, sorry for wasting your time and thanks for the help.

Thursday, April 1, 2021
 
Raef
 
1

If it's the linebreaks, you can try the brute-force method with:

$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/r*n+|r+/', $file));
print_r($data);

str_getcsv is available with PHP 5.3, or as workaround in the manual, via upgradephp or PHP_Compat.

Thursday, April 1, 2021
 
2

Output 0xEF 0xBB 0xBF before emitting the CSV data. Don't forget to increase the content length header by 3 if you handle it.

header('Content-type: text/csv;');
header('Content-Length: ' + strlen($content) + 3);
header('Content-disposition: attachment;filename=UK_order_' . date('Ymdhis') . '.csv');
echo "xefxbbxbf";
echo $content;
exit;
Thursday, April 1, 2021
 
LaKaede
 
5

This post solved my problem: https://stackoverflow.com/a/4762708/2349494

And this is what did the conversion:

print chr(255) . chr(254) . mb_convert_encoding($csv_output, 'UTF-16LE', 'UTF-8');

Earlier I was getting garbage characters now correct data is exported.

Thursday, April 1, 2021
 
Easen
 
2

Managed to answer my own question. With a bit of searching, I managed to find this little pdf here:

http://www.objectmentor.com/resources/articles/tfd.pdf

From there, I managed to adopt the code on page 35 to work with my program. All credit goes to Jeff Langr, 2001. All I did was make it work with some of Java's current standards.

Here's the code for all the people who may encounter this problem in the future.

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

public class CSVReader {

    private BufferedReader reader;
    private String line;
    private static final String DOUBLE_QUOTE = """;
    private static final String COMMENT_SYMBOL = "#";
    private static final char stateINIT = 'S';
    private static final char stateCOMMENT = '#';
    private static final char stateQUOTED_DATA = 'q';
    private static final char stateQUOTE_IN_QUOTED_DATA = 'Q';
    private static final char stateDATA = 'D';
    private static final char stateNEW_TOKEN = 'N';
    private static final char stateWHITESPACE = 'W';

    public CSVReader(String filename) throws IOException {
        reader = new BufferedReader(new java.io.FileReader(filename));
        loadNextNonCommentLine();
    }

    public ArrayList<String> next() throws IOException {
        if (line == null)
            throw new IOException("Read past end of file");
        ArrayList<String> columns = columnsFromCSVRecord(line);
        loadNextNonCommentLine();
        return columns;
    }

    public boolean hasNext() {
        return line != null;
    }

    void loadNextNonCommentLine() throws IOException {
        do
            line = reader.readLine();
        while (line != null && line.startsWith(COMMENT_SYMBOL));
        if (line == null)
            reader.close();
    }

    public ArrayList<String> columnsFromCSVRecord(String line) throws IOException {
        char state = stateINIT;
        char ch;
        int i = 0;
        ArrayList<String> tokens = new ArrayList<String>();
        StringBuffer buffer = new StringBuffer();
        char[] charArray = line.toCharArray();
        while (i < charArray.length) {
            ch = charArray[i++];
            switch (state) {
            case stateINIT:
                switch (ch) {
                case '"':
                    buffer.append(ch);
                    state = stateQUOTED_DATA;
                    break;
                case ',':
                    state = stateNEW_TOKEN;
                    tokens.add(clean(buffer));
                    buffer = new StringBuffer();
                    break;
                case 't':
                case ' ':
                    break;
                case '#':
                    state = stateCOMMENT;
                    break;
                default:
                    state = stateDATA;
                    buffer.append(ch);
                    break;
                }
                break;
            case stateCOMMENT:
                break;
            case stateQUOTED_DATA:
                switch (ch) {
                case '"':
                    buffer.append(ch);
                    state = stateQUOTE_IN_QUOTED_DATA;
                    break;
                default:
                    buffer.append(ch);
                    break;
                }
                break;
            case stateQUOTE_IN_QUOTED_DATA:
                switch (ch) {
                case '"':
                    state = stateQUOTED_DATA;
                    break;
                case ',':
                    state = stateNEW_TOKEN;
                    tokens.add(clean(buffer));
                    buffer = new StringBuffer();
                    break;
                case ' ':
                case 't':
                    break;
                case '#':
                    tokens.add(clean(buffer));
                    state = stateCOMMENT;
                    break;
                default:
                    throw new IOException("badly formed CSV record:" + line);
                }
                break;
            case stateDATA:
                switch (ch) {
                case '#':
                    tokens.add(clean(buffer));
                    state = stateCOMMENT;
                    break;
                case ',':
                    state = stateNEW_TOKEN;
                    tokens.add(clean(buffer));
                    buffer = new StringBuffer();
                    break;
                default:
                    buffer.append(ch);
                    break;
                }
                break;
            case stateNEW_TOKEN:
                switch (ch) {
                case '#':
                    tokens.add(clean(buffer));
                    state = stateCOMMENT;
                    break;
                case ',':
                    tokens.add(clean(buffer));
                    buffer = new StringBuffer();
                    break;
                case ' ':
                case 't':
                    state = stateWHITESPACE;
                    break;
                case '"':
                    buffer.append(ch);
                    state = stateQUOTED_DATA;
                    break;
                default:
                    state = stateDATA;
                    buffer.append(ch);
                    break;
                }
                break;
            case stateWHITESPACE:
                switch (ch) {
                case '#':
                    state = stateCOMMENT;
                    break;
                case ',':
                    state = stateNEW_TOKEN;
                    // ACCEPT NEW EMPTY COLUMN HERE??
                    break;
                case '"':
                    buffer.append(ch);
                    state = stateQUOTED_DATA;
                    break;
                case ' ':
                case 't':
                    break;
                default:
                    state = stateDATA;
                    buffer.append(ch);
                    break;
                }
                break;
            default:
                break;
            }
        }
        if (state == stateQUOTED_DATA)
            throw new IOException("Unmatched quotes in line:n" + line);
        if (state != stateCOMMENT)
            tokens.add(clean(buffer));
        return tokens;
    }

    public String clean(StringBuffer buffer) {
        String string = buffer.toString().trim();
        if (string.startsWith(DOUBLE_QUOTE))
            return string.substring(1, string.length() - 1);
        return string;
    }
}
Saturday, August 7, 2021
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :