保存为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. Pytorch 资料汇总(持续更新)

    1. Pytorch 论坛/网站 PyTorch 中文网 python优先的深度学习框架 Pytorch中文文档 Pythrch-CN文档地址 PyTorch 基礎篇 2. Pytorch 书籍 深度 ...

  2. u盘的一些理解

    U盘是由主控板+FLASH+外壳组成的,当主控板焊接上空白FLASH后插入电脑,因为没有相应的数据,  量产工具 电脑只能识别到主控板,而无法识别到FLASH,所以这时候电脑上显示出U盘盘符,但是双击 ...

  3. React-Native 之 网络请求 fetch

    前言 学习本系列内容需要具备一定 HTML 开发基础,没有基础的朋友可以先转至 HTML快速入门(一) 学习 本人接触 React Native 时间并不是特别长,所以对其中的内容和性质了解可能会有所 ...

  4. Ex 6_5棋子放置问题_第八次作业

    题目貌似有问题 (b) 子问题定义: 设maxValue[i][j]为棋盘的前i行中最后一行为i时第i行按照第j种放置方式放置时得到的最大覆盖值,comp[i][j]为第i种放置方式与第j种放置方式是 ...

  5. 类(字符串型;日期时间型;Math)

  6. dispatchers 设置

    Oracle连接方式(dispatchers 设置) oracle 响应客户端请求有两种方式: 1 专有连接:用一个服务器进程响应一个客户端请求 2 共享连接:用一个分派器(dispatcher)响应 ...

  7. 用javascript判断当前是安卓平台还是ios平台

    通常判断运行环境都是通过navigator.userAgent if (/android/gi.test(navigator.userAgent)){ // todo : android} if (/ ...

  8. fatal error: google/protobuf/arena.h:没有那个文件或目录

    安装caffe时make all会出现这个错误,按照https://github.com/BVLC/caffe/issues/4988说法,可能时libprotobuf-dev过时了,需要从源码重新变 ...

  9. LiteQuery MAX(Integer)、MAX(String) 判断是否返回值

    unit Unit6; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...

  10. BOM下的属性和方法---下

    继续BOM下的属性和方法---上 代码示例(亲测)2:   <title>location对象的属性</title> <script> //服务器环境我再此次演示中 ...