【问题标题】:exporting xls using csv使用 csv 导出 xls
【发布时间】:2012-10-09 07:19:08
【问题描述】:

我需要导出一个基于 .csv 文件的 .xls 文件,我可以导出相同的文件,但该文件一旦以 excel 格式打开就不会显示正确的结果。

这就是我所做的:

$filename = 'file';
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'), // this should be the heading
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
header("Pragma: public");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=".$filename.".xls");
header("Content-Transfer-Encoding: binary ");
echo file_get_contents($filename.".csv");

【问题讨论】:

  • 你到底想做什么?
  • “excel 格式不显示正确结果”是什么意思?请记住,这是您生成的 .csv 文件
  • 正确的结果,因为所有标题都以逗号分隔的单个标题出现,并且与行相同

标签: php csv xls


【解决方案1】:

您可以使用库 PHPExcel 创建 Excel。在这里您可以创建格式化的 XLS。

【讨论】:

    【解决方案2】:

    你为什么不做这样的事情:

    <?php
    
    $filename = 'file';
    
    header('Content-type: application/msexcel');
    header('Pragma: public');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header("Content-Disposition: attachment;filename=".$filename.".xls");
    
    $header = 'aaa'."\t".'bbb'."\t".'ccc'."\t".'dddd';
    $data   = '123'."\t".'456'."\t".'789'."\n";
    
    $data = $header."\n".$data;
    
    $data = trim($data)."\n";
    $data = str_replace("\r", "", $data);
    
    echo $data."\n";
    
    ?>
    

    【讨论】:

      【解决方案3】:

      我有 java 程序来做这件事。查看代码并尝试一下。这对我有用。在此我们需要将 csv 文件作为输入,并根据 csv 文件生成 excel 文件。为此,我们需要一个 jar 文件 jxl.jar。

        package com.sample.java.testing;
      
       import java.io.BufferedReader;
       import java.io.File;
       import java.io.FileReader;
       import java.io.IOException;
       import java.util.Locale;
       import jxl.CellView;
       import jxl.Workbook;
       import jxl.WorkbookSettings;
       import jxl.format.UnderlineStyle;
       import jxl.write.Label;
       import jxl.write.Number;
       import jxl.write.WritableCellFormat;
       import jxl.write.WritableFont;
       import jxl.write.WritableSheet;
       import jxl.write.WritableWorkbook;
       import jxl.write.WriteException;
       import jxl.write.biff.RowsExceededException;
      
          public class CSVToExcelSample {
      
      private WritableCellFormat timesBoldUnderline;
      private WritableCellFormat times;
      private String inputFile;
      
      //=========================================================================
      
      public void setOutputFile(String inputFile) {
          this.inputFile = inputFile;
      }
      
      //=========================================================================
      
      public void write() throws IOException, WriteException {
          File file = new File(inputFile);
          WorkbookSettings wbSettings = new WorkbookSettings();
          wbSettings.setLocale(new Locale("en", "EN"));
          WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
          workbook.createSheet("Report", 0);
          workbook.createSheet("Report1", 1);
          WritableSheet excelSheet = workbook.getSheet(0);
          WritableSheet excelSheet1 = workbook.getSheet(1);
          createLabel(excelSheet);
          createContent(excelSheet);
          createLabel(excelSheet1);
          createContent(excelSheet1);
          workbook.write();
          workbook.close();
      }
      
      //=========================================================================
      
      private void createLabel(WritableSheet sheet) throws WriteException {
          // Lets create a times font
          WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
          // Define the cell format
          times = new WritableCellFormat(times10pt);
          // Lets automatically wrap the cells
          times.setWrap(true);
          // Create create a bold font with unterlines
          WritableFont times10ptBoldUnderline = new WritableFont(
                  WritableFont.TIMES, 10, WritableFont.BOLD, false,
                  UnderlineStyle.SINGLE);
          timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
          // Lets automatically wrap the cells
          timesBoldUnderline.setWrap(true);
      
          CellView cv = new CellView();
          cv.setFormat(times);
          cv.setFormat(timesBoldUnderline);
          cv.setAutosize(true);
      
          // Write a few headers
          addCaption(sheet, 0, 0, "Header 1");
          addCaption(sheet, 1, 0, "This is another header");
      
      }
      
      //=========================================================================
      
      private void createContent(WritableSheet sheet) throws WriteException,
              RowsExceededException, IOException {
          // Write a few number
          /*
           * for (int i = 1; i < 10; i++) { // First column addNumber(sheet, 0, i,
           * i + 10); // Second column addNumber(sheet, 1, i, i * i); }
           * InputStream inputStream = new FileInputStream(file);
           * BufferedReader CSVFile = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
           */
          File file = new File("C:/code/csv/depression_scale.csv");
          BufferedReader CSVFile = new BufferedReader(new FileReader(file));
          int i = 1;
          // int j = 0;
          // int k = 0;
          String dataRow = CSVFile.readLine(); // Read the first line of data.
          // The while checks to see if the data is null. If it is, we've hit
          // the end of the file. If not, process the data.
          while (dataRow != null) {
              String[] dataArray = dataRow.split(",");
              int j = 0;
              for (String item : dataArray) {
                  System.out.print(item);
                  addLabel(sheet, j, i, item);
                  // i++;
                  j++;
              }
              i++;
              // k++;
              System.out.println(); // Print the data line.
              dataRow = CSVFile.readLine(); // Read next line of data.
          }
      
          // Close the file once all data has been read.
          CSVFile.close();
          // Lets calculate the sum of it
          /*
           * StringBuffer buf = new StringBuffer(); buf.append("SUM(A2:A10)");
           * Formula f = new Formula(0, 10, buf.toString()); sheet.addCell(f); buf
           * = new StringBuffer(); buf.append("SUM(B2:B10)"); f = new Formula(1,
           * 10, buf.toString()); sheet.addCell(f);
           * 
           * // Now a bit of text for (int i = 12; i < 20; i++) { // First column
           * addLabel(sheet, 0, i, "Boring text " + i); // Second column
           * addLabel(sheet, 1, i, "Another text"); }
           */
      }
      
      //=========================================================================
      
      private void addCaption(WritableSheet sheet, int column, int row, String s)
              throws RowsExceededException, WriteException {
          Label label;
          label = new Label(column, row, s, timesBoldUnderline);
          sheet.addCell(label);
      }
      
      //=========================================================================
      
      @SuppressWarnings("unused")
      private void addNumber(WritableSheet sheet, int column, int row,
              double integer) throws WriteException, RowsExceededException {
          Number number;
          number = new Number(column, row, integer, times);
          sheet.addCell(number);
      }
      
      //=========================================================================
      
      private void addLabel(WritableSheet sheet, int column, int row, String s)
              throws WriteException, RowsExceededException {
          Label label;
          label = new Label(column, row, s, times);
          sheet.addCell(label);
      }
      
      //=========================================================================
      
      public static void main(String[] args) throws WriteException, IOException {
      
      
          CSVToExcelSample test = new CSVToExcelSample();
          test.setOutputFile("filepathhere like C:/code/excel/lars.xls");
          test.write();
          System.out.println("Please check the result file under C:/code/excel/lars.xls ");
      }
      
      //=========================================================================
      

      }

      【讨论】:

        【解决方案4】:

        Read it 对于大多数开发人员来说,使用 PHP 从 MS Excel 文件中读取数据有时会很痛苦。之所以如此,是因为过去 PHP 和 xls 文件存在一些兼容性问题。此外,使用 PHP 在逗号分隔值 (csv) 文件中读取和操作数据比 Microsoft 拥有的专有格式更容易。解决此问题的一种最佳方法是将 xls 转换为 csv 格式。

        【讨论】:

          猜你喜欢
          • 2014-12-03
          • 2012-12-19
          • 1970-01-01
          • 2014-11-09
          • 2017-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-11
          相关资源
          最近更新 更多