DataTable保存为Excel或者Txt
保存为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的更多相关文章
- mfc 导出数据保存成excel和txt格式
最近做了一些东西,项目到了收尾的工作.不过这次我没有参与到控件机器的功能的那一部分,都是主管自己写的.不过,所有的控件重写都是由我来做的.还有数据库这一方面是我和主管共同完成的.不过还不错,主管写一部 ...
- [转].net 使用NPOI或MyXls把DataTable导出到Excel
本文转自:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.ht ...
- DataTable 导出到 Excel 类
底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> // ...
- 利用excel去除txt文本中重复项
2017-04-10 1.要去重的文件,点击右键,选择程序. 2.选择excel表格或者wps表格. 3.excel表格去重:选中单元格——数据——筛选——高级筛选——选择不重复记录——确定 wps表 ...
- 把 DataTable 输出到 excel 文件
''' <summary> ''' 把 DataTable 输出到 excel 文件 ''' </summary> ''' <param name="dt_da ...
- MySQL批量导入Excel、txt数据
MySQL批量导入Excel.txt数据 我想Excel是当今最大众化的批量数据管理软件了吧,所以我们会经常涉及到将Excel中数据导入到MySQL中的工作.网上有一些关于直接将Excel导入MySQ ...
- C# datatable 导出到Excel
datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <pa ...
- DataTable导出到Excel
简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...
- 将List下载到本地保存为Excel
直接附上代码 /// <summary> /// 将List保存为Excel /// </summary> /// <typeparam name="T&quo ...
随机推荐
- struts2在配置文件与JSP中用OGNL获取Action属性
参考:Struts与OGNL结合 struts2在配置文件中可以调用Action的属性,在JSP页面也可以取出Action的属性值(前提是属性有get,set方法). 第一个例子: 1.Action中 ...
- SpringBoot整合国际化功能
(1).编写国际化配置文件 在resources下新建i18n文件夹,并新建以下文件 ①index.properties username=username ②index_en_US.proper ...
- Kaggle Titanic补充篇
1.关于年龄Age 除了利用平均数来填充,还可以利用正态分布得到一些随机数来填充,首先得到已知年龄的平均数mean和方差std,然后生成[ mean-std, mean+std ]之间的随机数,然后 ...
- MCS-51单片机存储地址空间划分
1.前言 MCS-51的存储器有片内RAM.片外RAM 和 ROM 三个空间. MCS-51单片机在物理结构上有四个存储空间 1.片内程序存储器(片内ROM)2.片外程序存储器(片外ROM)3.片内数 ...
- Libevent源码分析—event_add()
接下来就是将已经初始化的event注册到libevent的事件链表上,通过event_add()来实现,源码位于event.c中. event_add() 这个函数主要完成了下面几件事: 1.将eve ...
- 字符串cookies转字典 scrapy使用。
配置文件 DOWNLOADER_MIDDLEWARES = { 'weibo.middlewares.CookiesMiddleware': 543, } 中间件内容 class CookiesMid ...
- 如何设置使eclipse修改代码不重启tomcat
tomcat配置 1.server.xml reloadable="true"<Context docBase="ins" path="/ins ...
- Weex学习资料整合
1.weex weex文档:http://weex.apache.org/cn/guide/index.html Weex Ui awesome-weex WEEX免费视频教程-从入门到放肆 (共17 ...
- HashMap Hashtable LinkedHashMap 和TreeMap
Map主要用于存储健值对,根据键得到值,因此不允许键重复(重复了覆盖了),但允许值重复.Hashmap 是一个最常用的Map,它根据键的HashCode值存储数据,根据键可以直接获取它的值,具有很快的 ...
- Transformer+BERT+GPT+GPT2
Transformer: https://jalammar.github.io/illustrated-transformer/ BERT: https://arxiv.org/pdf/1810.04 ...
