保存为txt的时候,可保持原来的行列对齐,如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Reflection; namespace celiang
{
public class saveDataTableToExcelTxt
{
public saveDataTableToExcelTxt(DataTable table,string fullName)
{
string extention = Path.GetExtension(fullName);
if(extention==".txt")//如果保存为txt文件
{
if(ExportToTxt(table,fullName)==true)
{
MessageBox.Show("保存成功","提示");
}
}
else if(extention==".xls")
{
if (ExportToExcel(table, fullName))
{
MessageBox.Show("保存成功","提示");
}
} }
/// <保存DataTable 到Excel>
///
/// </summary>
/// <param name="table"></param>
/// <param name="excelName"></param>
/// <returns></returns>
private bool ExportToExcel(System.Data.DataTable table, string excelName)
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel.Workbook oWB;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRange; // Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application(); // Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false; // Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value); // Get the active sheet
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Customers"; // Process the DataTable
// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
System.Data.DataTable dt = table; int rowCount = ;
foreach (DataRow dr in dt.Rows)
{
rowCount += ;
for (int i = ; i < dt.Columns.Count + ; i++)
{
// Add the header the first time through
if (rowCount == )
{
oSheet.Cells[, i] = dt.Columns[i - ].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - ].ToString();
}
} // Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[, ],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit(); // Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(excelName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit(); // Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect(); return true;
} private bool ExportToTxt(System.Data.DataTable table ,string fullName)
{
int[] iColumnLength = new int[table.Columns.Count];
FileStream fileStream = new FileStream(fullName, FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream, System.Text.Encoding.Unicode);
StringBuilder strBuilder = new StringBuilder(); for (int i = ; i < table.Columns.Count; i++)
{
int iLength = ;
for (int j = ; j < table.Rows.Count; j++)
{
if (iLength < (table.Rows[j][i].ToString()).Length)
{
iLength = (table.Rows[j][i].ToString()).Length;
}
}
iColumnLength[i] = iLength;
} for (int i = ; i < table.Rows.Count - ; i++)
{ for (int j = ; j < table.Columns.Count; j++)
{
string str1 = table.Rows[i][j].ToString();
int iLength = str1.Length;
int iColumnWidth = iColumnLength[j] + ;
for (int k = iLength; k < iColumnWidth; k++)
{
str1 += " ";
}
if (j == table.Columns.Count - )
{
strBuilder.AppendLine(str1);
}
else
{
strBuilder.Append(str1);
}
}
} streamWriter.WriteLine(strBuilder.ToString());
streamWriter.Close();
fileStream.Close();
return true;
}
}
}

DataTable保存为Excel或者Txt的更多相关文章

  1. mfc 导出数据保存成excel和txt格式

    最近做了一些东西,项目到了收尾的工作.不过这次我没有参与到控件机器的功能的那一部分,都是主管自己写的.不过,所有的控件重写都是由我来做的.还有数据库这一方面是我和主管共同完成的.不过还不错,主管写一部 ...

  2. [转].net 使用NPOI或MyXls把DataTable导出到Excel

    本文转自:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.ht ...

  3. DataTable 导出到 Excel 类

    底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> // ...

  4. 利用excel去除txt文本中重复项

    2017-04-10 1.要去重的文件,点击右键,选择程序. 2.选择excel表格或者wps表格. 3.excel表格去重:选中单元格——数据——筛选——高级筛选——选择不重复记录——确定 wps表 ...

  5. 把 DataTable 输出到 excel 文件

    ''' <summary> ''' 把 DataTable 输出到 excel 文件 ''' </summary> ''' <param name="dt_da ...

  6. MySQL批量导入Excel、txt数据

    MySQL批量导入Excel.txt数据 我想Excel是当今最大众化的批量数据管理软件了吧,所以我们会经常涉及到将Excel中数据导入到MySQL中的工作.网上有一些关于直接将Excel导入MySQ ...

  7. C# datatable 导出到Excel

    datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <pa ...

  8. DataTable导出到Excel

    简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...

  9. 将List下载到本地保存为Excel

    直接附上代码 /// <summary> /// 将List保存为Excel /// </summary> /// <typeparam name="T&quo ...

随机推荐

  1. nginx入门一

    配置文件: server_name user root; worker_processes 2; error_log logs/error-test.log; #pid logs/nginx.pid; ...

  2. SpringBoot整合Jdbc

    (1).添加相关依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId ...

  3. 【CTF REVERSE】ctf02-查找字符串

    1.前言 公司大拿给写的一个CTF逆向程序,提升我们组内人员的水平. 基于对话框MFC框架开发,使用EDIT控制特性隐藏Flag,可借助spy4win之类窗体工具找出Flag. 程序加UPX壳,已对壳 ...

  4. [转]Linux下的链接脚本基础

    [转]http://linux.chinaunix.net/techdoc/beginner/2009/08/12/1129972.shtml 1. 前言 (1)每一个链接过程都由链接脚本(linke ...

  5. NandFlash和iNand

    nand 1.nand的单元组织:block与page(大页Nand与小页Nand)(1)Nand的页和以前讲过的块设备(尤其是硬盘)的扇区是类似的.扇区最早在磁盘中是512字节,后来也有些高级硬盘扇 ...

  6. MySQL 误操作后数据恢复(update,delete忘加where条件)【转】

    在数据库日常维护中,开发人员是最让人头痛的,很多时候都会由于SQL语句 写的有问题导致服务器出问题,导致资源耗尽.最危险的操作就是在做DML操作的时候忘加where条件,导致全表更新,这是作为运维或者 ...

  7. Centos6.5使用yum安装mysql——快速上手必备

    第1步.yum安装mysql [root@stonex ~]#  yum -y install mysql-server 安装结果: Installed:     mysql-server.x86_6 ...

  8. Idea xml 粘贴文本保持原有格式

    setting->Editor->Code Style->XML 在右边的面板中,单击第二个 “Other” 的页签,勾选“Keep white spaces”,重启idea.

  9. Coursera台大机器学习技法课程笔记05-Kernel Logistic Regression

    这一节主要讲的是如何将Kernel trick 用到 logistic regression上. 从另一个角度来看soft-margin SVM,将其与 logistic regression进行对比 ...

  10. 基于GTID环境的数据恢复

    下面说一个线上环境的数据恢复案例,线上环境误操作的事情,随时都有可能发生的,这时候运维DBA或者DBA会想,没人会傻到把数据库干掉的吧?又或者没有会闲得蛋痛删除了几条数据又想恢复这么无聊吧?适适这样的 ...