保存为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. Linux动态频率调节系统CPUFreq之一:概述【转】-- 非常好的博客

    转自:http://blog.csdn.net/droidphone/article/details/9346981     目录(?)[-] sysfs接口 软件架构 cpufreq_policy ...

  2. 理解 Linux 配置文件【转】

    转自:http://www.ibm.com/developerworks/cn/linux/management/configuration/ 分类和使用 本文说明了 Linux 系统的配置文件,在多 ...

  3. 网络抓包 Fiddler

    1. Fiddler 抓包简介 Fiddler是通过改写HTTP代理,让数据从它那通过,来监控并且截取到数据.当然Fiddler很屌,在打开它的那一瞬间,它就已经设置好了浏览器的代理了.当你关闭的时候 ...

  4. 转载:磁盘目录(1.3.3)《深入理解Nginx》(陶辉)

    原文:https://book.2cto.com/201304/19614.html 要使用Nginx,还需要在Linux文件系统上准备以下目录. (1)Nginx源代码存放目录 该目录用于放置从官网 ...

  5. vue-router两种模式,到底什么情况下用hash,什么情况下用history模式呢?

    转:https://segmentfault.com/q/1010000010340823/a-1020000010598395 为什么要有 hash 和 history 对于 Vue 这类渐进式前端 ...

  6. ios 侧边手势滑动返回 禁用/开启 功能

    // 禁用  返回手势       if ([self.navigationController respondsToSelector:@selector(interactivePopGestureR ...

  7. python恶俗古风诗自动生成器

    # -*- coding:utf-8 -*- #模仿自: http://www.jianshu.com/p/f893291674ca#python恶俗古风诗自动生成器from random impor ...

  8. cf Queries on a String

    #include<iostream> #include<cstring> #include<cstdio> using namespace std; #define ...

  9. 【转】角落的开发工具集之Vs(Visual Studio)2017插件推荐

    因为最近录制视频的缘故,很多朋友都在QQ群留言,或者微信公众号私信我,问我一些工具和一些插件啊,怎么使用的啊?那么今天我忙里偷闲整理一下清单,然后在这里面公布出来. Visual Studio 201 ...

  10. DOM编程艺术推荐的addLoadEvent和insertAfter

    addLoadEvent.js function addLoadEvent(func){ var oldonLoad = window.onload; if(typeof window.onload! ...