保存为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. js常用的工具函数

    JS选取DOM元素的方法注意:原生JS选取DOM元素比使用jQuery类库选取要快很多1.通过ID选取元素document.getElementById('myid');2.通过CLASS选取元素do ...

  2. 使用layer 弹出对话框 子父页面相互参数传递 父页面获取子页面参数实例

    一.先看效果: 1.点击三个点的图标弹出了子页面: 2.子页面调用父页面方法,图一调用父页面方法,图二得到父页面var变量.           3.选择之后,关闭弹框,父页面得到子页面单选框选择的v ...

  3. MAC上mongodb连接不上

    1.在Mac客户端里输入 mongo,发现mongo连接不上了,原因是mongo的服务没有开启. 2.在命令行了输入 mongod,开启服务的命令 3.启动起来以后,用mongo连接服务器.

  4. 生成ansible-playbook的yaml文件的代码(字典排序问题无法解决)

    import yaml import collections def add_task(): return None def add_vars(): return None def add_handl ...

  5. zabbix系列(二)zabbix3.0.4添加对mysql数据库性能的监控

    zabbix3.0.4添加Mysql的监控 zabbix3.0 server已自带mysql的模板了,只需安装agent端,然后在web端给主机增加模板就行了. Agent端操纵 /etc/zabbi ...

  6. OneNET麒麟座应用开发之九:与SD卡通讯并保存数据

    由于需要记录的数据量比较大,而且有些时候,有的用户不方便实时上传数据,所以要求使用SD卡存储数据然后人工收取上传.为此我们选择了一种通用的SD卡读写器. 1.读卡器简介 该读卡器整合 SD 卡规范和 ...

  7. tsconfig.json配置

    什么工具看什么官网-一般都会有说明的 https://www.tslang.cn/docs/handbook/tsconfig-json.html 概述 如果一个目录下存在一个tsconfig.jso ...

  8. sublime text 3配置c/c++编译环境

    关于gcc和g++ 安装编译器是后面所有工作的基础,如果没有编译器,后面的一切都无从谈起.在windows下使用gcc和g++,是通过安装MinGW实现的. 安装MinGW MinGW是Minimal ...

  9. 【转】js中的事件委托或是事件代理详解

    起因: 1.这是前端面试的经典题型,要去找工作的小伙伴看看还是有帮助的: 2.其实我一直都没弄明白,写这个一是为了备忘,二是给其他的知其然不知其所以然的小伙伴们以参考: 概述: 那什么叫事件委托呢?它 ...

  10. composer卸载重装

    $ composer remove phpunit/phpunit --dev $ composer require phpunit/phpunit --dev