Writes a CSV file

@param columnHeaders headers
@param rows rows
@return CSV file
@throws IOException throws IOException when CSV writing fails
558414
private static byte[] writeCsv(String[] columnHeaders, List<String[]> rows) throws IOException {
    return writeCsv(columnHeaders, rows.stream().toArray(String[][]::new));
  }
639246
public function setCsvContent($rows, $name, $header = null)
    {
        $this->setAttachment(pathinfo($name, PATHINFO_EXTENSION) === 'csv' ? $name : $name . '.csv');

        $file = fopen('php://temp', 'rb+');
        fprintf($file, "\xEF\xBB\xBF");

        if (is_string($header)) {
            $header = explode(',', $header);
        } elseif ($header === null && $first = current($rows)) {
            $header = array_keys(is_array($first) ? $first : $first->toArray());
        }

        if ($header !== null) {
            fputcsv($file, $header);
        }

        foreach ($rows as $row) {
            fputcsv($file, is_array($row) ? $row : $row->toArray());
        }

        rewind($file);
        $content = stream_get_contents($file);
        fclose($file);

        $this->setContentType('text/csv');
        $this->setContent($content);

        return $this;
    }
979197
def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
        '''  '''
        if not quoting:
            quoting = csv.QUOTE_MINIMAL
        if 'lineterminator' not in kwargs:
            kwargs['lineterminator'] = '\n'  # use \n to fix double-line in Windows
        with open(path, mode='wt', newline='') as csvfile:
            if fieldnames:
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=dialect, quoting=quoting, extrasaction=extrasaction, *args, **kwargs)
                writer.writeheader()
                for row in rows:
                    writer.writerow(row)
            else:
                writer = csv.writer(csvfile, dialect=dialect, quoting=quoting, *args, **kwargs)
                for row in rows:
                    writer.writerow(row)
892675
protected void writeCsv(final MBasicTable table, final OutputStream outputStream,
			final DateFormat dateFormat) throws IOException {
		// récupération des informations utiles
		final int columnCount = table.getColumnModel().getColumnCount();
		final int rowCount = table.getRowCount();
		final String charset = System.getProperty("file.encoding");
		final Writer out = new OutputStreamWriter(outputStream, charset);

		final char csvSeparator = CSV_SEPARATOR;
		// le séparateur des .csv (',' à l'américaine)
		final NumberFormat decimalFormat = NumberFormat.getInstance(Locale.US);
		decimalFormat.setGroupingUsed(false);
		final String eol = System.getProperty("line.separator");

		// titres des colonnes
		writeCsvHeader(table, out, csvSeparator);

		// les données proprement dites (ligne par ligne puis colonne par colonne)
		Object value;
		String text;
		for (int k = 0; k < rowCount; k++) {
			for (int i = 0; i < columnCount; i++) {
				value = getValueAt(table, k, i);

				if (value instanceof Number) {
					text = decimalFormat.format(value);
				} else if (value instanceof Date) {
					text = dateFormat.format(value);
				} else if (value instanceof Boolean) {
					text = value.toString();
				} else {
					text = getTextAt(table, k, i);
					text = formatCsv(text, csvSeparator);
				}

				out.write(text);
				if (i < columnCount - 1) {
					out.write(csvSeparator);
				}
			}
			if (k < rowCount - 1) {
				out.write(eol);
			}
		}
		out.flush();
	}
1372670
public void write(String... columns) throws DataUtilException {
        if(columns.length != tableColumns) {
            throw new DataUtilException("Invalid column count. Expected " + tableColumns + " but found: "
                    + columns.length);
        }
        try {
            if(currentRow == 0) {
                // capture header row
                this.headerRowColumns = columns;
                writeTop();
                writeRow(headerRowColumns);
            } else if(maxRowsPerPage > 1 && currentRow % maxRowsPerPage == 0) {
                writeBottom(true);
                currentPageNumber = (currentRow/maxRowsPerPage) + 1;
                writeTop();
                writeRow(headerRowColumns);
                currentRow += 1;
                writeRow(columns);
            } else {
                writeRow(columns);
            }
            currentRow += 1;
        } catch (Exception e) {
            throw new DataUtilException(e);
        }
    }
992511
public function format(array $rows, array $headers = []) : string
    {
        if (count($rows) === 0) {
            return '';
        }

        foreach ($rows as &$row) {
            $row = (array)$row;
        }

        unset($row);

        // If there are headers, we want them to be formatted along with the rows
        $headersAndRows = count($headers) === 0 ? $rows : array_merge([$headers], $rows);
        $headersAndRows = count($headers) === 0 ? $rows : array_merge([$headers], $rows);
        $maxLengths = $this->padding->normalizeColumns($headersAndRows);
        $eolChar = $this->padding->getEolChar();
        $rowText = explode($eolChar, $this->padding->format($headersAndRows, function ($row) {
            return sprintf(
                '%s%s%s%s%s',
                $this->verticalBorderChar,
                $this->cellPaddingString,
                implode($this->cellPaddingString . $this->verticalBorderChar . $this->cellPaddingString, $row),
                $this->cellPaddingString,
                $this->verticalBorderChar
            );
        }));

        // Create the borders
        $borders = [];

        foreach ($maxLengths as $maxLength) {
            $borders[] = str_repeat($this->horizontalBorderChar, $maxLength + 2 * mb_strlen($this->cellPaddingString));
        }

        $borderText = $this->intersectionChar . implode($this->intersectionChar, $borders) . $this->intersectionChar;
        $headerText = count($headers) > 0 ? array_shift($rowText) . $eolChar . $borderText . $eolChar : '';

        return $borderText . $eolChar . $headerText . implode($eolChar, $rowText) . $eolChar . $borderText;
    }
1289948
@Override
    public void insertRow(Object[] values) throws IOException {
        checkWriter();
        if(values.length != getDbaseFileHeader().getNumFields()) {
            throw new IllegalArgumentException("Incorrect field count "+values.length+" expected "+getFieldCount());
        }
        try {
            dbaseFileWriter.write(values);
        } catch (DbaseFileException ex) {
            throw new IOException(ex.getLocalizedMessage(), ex);
        }
    }
257127
public ExcelExporter setColumnsHeader(List<String> columnsHeader) {
		noOfCols = columnsHeader.size();

		sheet.createFreezePane(0, 1);
		SXSSFRow headerRow = sheet.createRow(0);

		for (int i = 0; i < columnsHeader.size(); i++) {
			String cellHeader = columnsHeader.get(i);
			writeCell(headerRow, i, cellHeader, headerStyle);
		}
		return this;
	}
230225
private void setupMappingColumns(final String[] headers) {
        
        final List<ColumnMapping> columnMappingList = beanMapping.getColumns();
        final HeaderMapper headerMapper = beanMapping.getHeaderMapper();
        
        // 一致するラベルがあれば、カラムの番号を補完する
        final int headerSize = headers.length;
        for(int i=0; i < headerSize;i ++) {
            
            final String header = headers[i];
            
            /*
             * 番号が決まっておらず、ラベルが一致するカラム情報を抽出する。
             * ※既に番号が決まっているが、ラベルが一致しないのものは、後からチェックする。
             */
            List<ColumnMapping> undeterminedColumnList = columnMappingList.stream()
                .filter(col -> !col.isDeterminedNumber())
                .filter(col -> headerMapper.toMap(col, beanMapping.getConfiguration(), beanMapping.getGroups()).equals(header))
                .collect(Collectors.toList());
            
            final int columnNumber = i+1;
            undeterminedColumnList.forEach(col -> col.setNumber(columnNumber));
            
        }
        
        // カラムの番号順に並び変える
        columnMappingList.sort(null);
        
        /* 
         * ヘッダーでは指定されていない番号が未決定のカラムについて、空いている番号に振る
         * ・@CsvPartialで指定した場合とかぶらないようにすべき？
         */
        final Optional<CsvPartial> partialAnno = Optional.ofNullable(beanMapping.getType().getAnnotation(CsvPartial.class));
        final List<ColumnMapping> undeterminedColumnList = columnMappingList.stream()
                .filter(col -> !col.isDeterminedNumber())
                .collect(Collectors.toList());
        
        if(!undeterminedColumnList.isEmpty()) {
            final Set<Integer> determinedNumbers = columnMappingList.stream()
                    .filter(col -> col.isDeterminedNumber())
                    .map(col -> col.getNumber())
                    .collect(Collectors.toSet());
            
            // @CsvParitalで定義されているカラムは、決定されている番号として処理する。
            partialAnno.ifPresent(anno -> Arrays.stream(anno.headers()).forEach(header -> determinedNumbers.add(header.number())));
            
            int counter = 1;
            for(ColumnMapping col : undeterminedColumnList) {
                while(true) {
                    if(!determinedNumbers.contains(counter)) {
                        break;
                    }
                    counter++;
                }
                
                col.setNumber(counter);
                determinedNumbers.add(counter);
            }
            
            // 第度カラムの番号順に並び変える
            columnMappingList.sort(null);
        
        }
        
        // 決定していないカラム番号のチェック
        BeanMappingFactoryHelper.validateNonDeterminedColumnNumber(beanMapping.getType(), columnMappingList, headers);
        
        // 重複しているカラム番号のチェック
        BeanMappingFactoryHelper.validateDuplicatedColumnNumber(beanMapping.getType(), columnMappingList);
        
        // 不足しているカラム番号の補完
        BeanMappingFactoryHelper.supplyLackedNumberMappingColumn(beanMapping.getType(), columnMappingList, partialAnno, headers);
        
        beanMapping.setColumns(columnMappingList);
        
    }
1037393
public static void writeCSVColumns(XYSeries series, String path2Dir) {

    File newFile = new File(path2Dir + series.getName() + ".csv");
    Writer out = null;
    try {

      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF8"));
      double[] xData = series.getXData();
      double[] yData = series.getYData();
      double[] errorBarData = series.getExtraValues();
      for (int i = 0; i < xData.length; i++) {

        StringBuilder sb = new StringBuilder();
        sb.append(xData[i]).append(",");
        sb.append(yData[i]).append(",");
        if (errorBarData != null) {
          sb.append(errorBarData[i]).append(",");
        }
        sb.setLength(sb.length() - 1);
        sb.append(System.getProperty("line.separator"));

        // String csv = xDataPoint + "," + yDataPoint + errorBarValue == null ? "" : ("," +
        // errorBarValue) + System.getProperty("line.separator");
        // String csv = + yDataPoint + System.getProperty("line.separator");
        out.write(sb.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        try {
          out.flush();
          out.close();
        } catch (IOException e) {
          // NOP
        }
      }
    }
  }
908629
def write_text_rows(writer, rows):
    ''''''
    for row in rows:
        try:
            writer.writerow(row)
        except UnicodeEncodeError:
            # Python 2 csv does badly with unicode outside of ASCII
            new_row = []
            for item in row:
                if isinstance(item, text_type):
                    new_row.append(item.encode('utf-8'))
                else:
                    new_row.append(item)
            writer.writerow(new_row)
157054
public String getCsv() {

        StringWriter writer = new StringWriter();
        try (CSVWriter csv = new CSVWriter(writer)) {
            List<String> headers = new ArrayList<>();
            for (String col : m_columns) {
                headers.add(col);
            }
            csv.writeNext(headers.toArray(new String[] {}));
            for (List<Object> row : m_data) {
                List<String> colCsv = new ArrayList<>();
                for (Object col : row) {
                    colCsv.add(String.valueOf(col));
                }
                csv.writeNext(colCsv.toArray(new String[] {}));
            }
            return writer.toString();
        } catch (IOException e) {
            return null;
        }
    }
782171
def write(self, data, method='w'):
        
        # Create list of lists from flat list
        data = data if isinstance(data[0], (list, set, tuple)) else [[d] for d in data]

        # Open file and write rows
        with open(self.file_path, method) as write:
            wr = csv_builtin.writer(write)
            wr.writerows(data)
        return self.file_path
405568
public void generateCsv(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
        ICsvMapWriter csvWriter = null;
        try {
            csvWriter = new CsvMapWriter(new OutputStreamWriter(out), CsvPreference.STANDARD_PREFERENCE);
            // the header elements are used to map the bean values to each column (names must match)
            String[] header = new String[] {};
            CellProcessor[] processors = new CellProcessor[] {};
            if (columns != null)
            {
                header = (String[])CollectionUtils.collect(columns, new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        ColumnDef column = (ColumnDef)input;
                        return column.getName();
                    }
                }).toArray(new String[0]) ;
                processors = (CellProcessor[]) CollectionUtils.collect(columns, new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        return new Optional();
                    }
                }).toArray(new CellProcessor[0]);
            } else if (rows.size() > 0)
            {
                header = new ArrayList<String>(rows.get(0).keySet()).toArray(new String[0]);
                processors = (CellProcessor[]) CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        return new Optional();
                    }
                }).toArray(new CellProcessor[0]);
            }
            if (header.length > 0)
                csvWriter.writeHeader(header);
            if (rows != null)
                for (Map<String, Object> row : rows)
                {
                    csvWriter.write(row, header, processors);
                }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            if( csvWriter != null ) {
                try {
                    csvWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
    }
1011339
@SafeVarargs
  public final TypedDataSet<T> rows(T... rows)  {
    for (T rowObj : rows) {
      super.row(conv.convert(rowObj));
    }
    return this;
  }
482497
public void write(Writer out)
         throws IOException
    {
        writeHtmlHead(out);
        
        out.write("<frameset "+border);
        
        if(colSpec!=null)
            out.write(" cols=\""+colSpec+"\"");
        if(rowSpec!=null)
            out.write(" rows=\""+rowSpec+"\"");
        out.write(">");

        for(int r=0;r<rows;r++)
            for(int c=0;c<cols;c++)
                frames[c][r].write(out);

        out.write("<noframes>");
        writeElements(out);
        out.write("</noframes>");

        out.write("</frameset>");
        out.write("</html>");
    }
6602
protected void writeRow(final String... columns) throws IOException {
		
		if( columns == null ) {
			throw new NullPointerException(String.format("columns to write should not be null on line %d", lineNumber));
		} else if( columns.length == 0 ) {
			throw new IllegalArgumentException(String.format("columns to write should not be empty on line %d",
				lineNumber));
		}
		
		StringBuilder builder = new StringBuilder();
		for( int i = 0; i < columns.length; i++ ) {
			
			columnNumber = i + 1; // column no used by CsvEncoder
			
			if( i > 0 ) {
				builder.append((char) preference.getDelimiterChar()); // delimiter
			}
			
			final String csvElement = columns[i];
			if( csvElement != null ) {
				final CsvContext context = new CsvContext(lineNumber, rowNumber, columnNumber);
				final String escapedCsv = encoder.encode(csvElement, context, preference);
				builder.append(escapedCsv);
				lineNumber = context.getLineNumber(); // line number can increment when encoding multi-line columns
			}
			
		}
		
		builder.append(preference.getEndOfLineSymbols()); // EOL
		writer.write(builder.toString());
	}