Datetable Convert TO CSV

// C# Code

public static class Rfc4180Writer
{
    public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
    {
        if (includeHeaders) {
            IEnumerable<String> headerValues = sourceTable.Columns
                .OfType<DataColumn>()
                .Select(column => QuoteValue(column.ColumnName));

            writer.WriteLine(String.Join(",", headerValues));
        }

        IEnumerable<String> items = null;

        foreach (DataRow row in sourceTable.Rows) {
            items = row.ItemArray.Select(o => QuoteValue(o.ToString()));
            writer.WriteLine(String.Join(",", items));
        }

        writer.Flush();
    }

    private static string QuoteValue(string value)
    {
        return String.Concat("\"",
        value.Replace("\"", "\"\""), "\"");
    }
} 

-------------------------------------------------------------------------------------------------------------------------------------------------------------->
// C# Code
public static class Program {
    public static void Main() {
        DataTable sourceTable = new DataTable();

        sourceTable.Columns.AddRange(new DataColumn[] {
            new DataColumn("ID", typeof(Guid)),
            new DataColumn("Date", typeof(DateTime)),
            new DataColumn("StringValue", typeof(string)),
            new DataColumn("NumberValue", typeof(int)),
            new DataColumn("BooleanValue", typeof(bool))
        });

        sourceTable.Rows.Add(Guid.NewGuid(), DateTime.Now, "String1", 100, true);
        sourceTable.Rows.Add(Guid.NewGuid(), DateTime.Now, "String2", 200, false);
        sourceTable.Rows.Add(Guid.NewGuid(), DateTime.Now, "String3", 300, true);

        using (StreamWriter writer = new StreamWriter("C:\\Temp\\dump.csv")) {
            Rfc4180Writer.WriteDataTable(sourceTable, writer, true);
        }
    }
} 

___________________________________________________________________________________________>

For the ASP.NET MVC    
// C# Code
public class ReportController : Controller
{
    [HttpGet()]
    public ActionResult Export()
    {
        DataTable sourceTable = new DataTable();

        sourceTable.Columns.AddRange(new DataColumn[] {
            new DataColumn("ID", typeof(Guid)),
            new DataColumn("Date", typeof(DateTime)),
            new DataColumn("StringValue", typeof(string)),
            new DataColumn("NumberValue", typeof(int)),
            new DataColumn("BooleanValue", typeof(bool))
        });

        sourceTable.Rows.Add(Guid.NewGuid(), DateTime.Now, "String1", 100, true);
        sourceTable.Rows.Add(Guid.NewGuid(), DateTime.Now, "String2", 200, false);
        sourceTable.Rows.Add(Guid.NewGuid(), DateTime.Now, "String3", 300, true);

        byte[] outputBuffer = null;

        using (MemoryStream tempStream = new MemoryStream()) {
            using (StreamWriter writer = new StreamWriter(tempStream)) {
                Rfc4180Writer.WriteDataTable(sourceTable, writer, true);
            }

            outputBuffer = tempStream.ToArray();
        }

        return File(outputBuffer, "text/csv", "export.csv");
    }
} 
				
时间: 2024-11-18 01:16:34

Datetable Convert TO CSV的相关文章

magento 上传csv表格中实例化对象例子

app\code\core\Mage\Dataflow\Model\Convert\Parser\csv.php 文件是后台上传csv,插入到dataflow_batch_import中转表的代码,有如下代码片段 1.$batchModel = $this->getBatchModel(); 2.$batchModel->setParams($this->getVars()) ->setAdapter($adapterName) ->save(); 从上往下看, 第一行$th

spring 里面的StringUtils,先放这儿,有时间研究吧

/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://

表数据文件DBF的读取和写入操作

import sys import csv import struct import datetime import decimal import itertools from cStringIO import StringIO from operator import itemgetter def dbfreader(f): """Returns an iterator over records in a Xbase DBF file. The first row retu

`cocos2dx非完整` 开始自己的FW模块

上一篇的文章中说到了一些个人习惯的东西以及一些简单的项目配置,这一篇文章我们来进一步完善一些东西.首先,打开编译以后的客户端执行,会看到一大堆的fileutils加载luac文件的提示,在终端显示一大堆,挺烦人的,我做的第一件事就是去修改他.这个很简单,有两种做法,第一种是在c++部分添加调用 1 cocos2d::FileUtils::getInstance()->setPopupNotify(false); 当然也可以在lua部分添加, 1 cc.FileUtils:getInstance(

python读写dbf文件

Python读写dbf文件 # coding=utf8 """ A reader and writer for dbf file.see http://code.activestate.com/recipes/362715/ for moe detail """ import struct import datetime import decimal import itertools def dbfreader(f):     "&qu

MatterTrack Route Of Network Traffic :: Matter

Python 1.1?基础 while语句 字符串边缘填充 列出文件夹中的指定文件类型 All Combinations For A List Of Objects Apply Operations Over Items In A List Applying Functions To List Items Arithmetic Basics Assignment Operators Basic Operations With NumPy Array Breaking Up String Vari

csharp: datagridview Convert csv file

/// <summary> /// 保存文件 /// 涂聚文 /// 2014-08-29 /// Geovin Du /// </summary> /// <param name="dGV"></param> /// <param name="filename"></param> public static void DataGridViewToCsV(DataGridView dGV, st

goalng导出excel(csv格式)

最近项目中有个小需求,需要将查询结果导出到excel.之间前java比较容易,使用POI很容易就能实现,查了下golang的文档,发现golang下边并没有导出excel的包,但是却有一个encoding/csv的包,看了下发现可以导出csv文件,大家都知道csv文件其实就是文本格式的excel文件,可以直接通过excel打开或是导入excel. 看起来挺好的,问题如愿解决,但是事实证明对已一个还不成熟的语言或是库最好还是先测一下的好.兴冲冲的卸了测试例子,成功导出了一个text.csv文件,一

DataTable数据导出CSV文件

public static void SaveAsExcel(DataTable dt1) { //System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();// = new SaveFileDialog(); //sfd.Filter = "导出文件 (*.csv)|*.csv"; //sfd.FilterIndex = 0; //sfd.RestoreDirectory =