C#-FileHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Collections;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Drawing; namespace Common
{
public class FileHelper
{
public static DataTable TxtToDataTable(string Path)
{
DataTable dt = new DataTable();
ArrayList arrayList = new ArrayList();
StreamReader sr = new StreamReader(Path, Encoding.Default);
string line;
while ((line = sr.ReadLine()) != null)
{
arrayList.Add(line);
}
sr.Close();
string[] arrDN = null;
for (int intLine = ; intLine < arrayList.Count; intLine++)
{
arrDN = arrayList[intLine].ToString().Split(new char[] { '\t' });
if (intLine == ) // Add Colunm
{
for (int m = ; m < arrDN.Length; m++)
{
dt.Columns.Add(arrDN[m].ToString());
}
}
else
{
dt.LoadDataRow(arrDN, true); } }
return dt;
}
public static bool DataTableToTxt(DataTable dt, string Path)
{ //SaveFileDialog saveFileDialog1 = new SaveFileDialog(); //saveFileDialog1.Filter = "txt(*.txt)|*.txt"; //saveFileDialog1.FilterIndex = 0; //saveFileDialog1.RestoreDirectory = true; //saveFileDialog1.CreatePrompt = true; //saveFileDialog1.Title = "导出txt文件到 "; //DateTime now = DateTime.Now; //saveFileDialog1.FileName = now.Second.ToString().PadLeft(2, '0'); ////now.Year.ToString().PadLeft(2)+now.Month.ToString().PadLeft(2, '0 ') +now.Day.ToString().PadLeft(2, '0 ')+ "_ " +now.Hour.ToString().PadLeft(2, '0 ') +now.Minute.ToString().PadLeft(2, '0 ') + //saveFileDialog1.ShowDialog(); try
{ FileStream myStream = new FileStream(Path, FileMode.Create); //StreamWriter sw=new StreamWriter(myStream,System.Text.Encoding.GetEncoding( "gb2312 ")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); String str = " "; //写标题 for (int i = ; i < dt.Columns.Count; i++)
{ if (i > )
{ str += "\t "; } str += dt.Columns[i].ColumnName; } sw.WriteLine(str); //写内容 for (int rowNo = ; rowNo < dt.Rows.Count; rowNo++)
{ String tempstr = " "; for (int columnNo = ; columnNo < dt.Columns.Count; columnNo++)
{ if (columnNo > )
{ tempstr += "\t "; } //tempstr+=dg.Rows[rowNo,columnNo].ToString(); tempstr += dt.Rows[rowNo][columnNo].ToString(); } sw.WriteLine(tempstr); } sw.Close(); myStream.Close();
return true;
}
catch (Exception)
{
return false;
} }
public static DataTable CSVToDataTable(string Path)
{
System.Data.DataTable dt = new System.Data.DataTable();
FileStream fs = new FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = ;
//标示是否是读取的第一行
bool IsFirst = true; //逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
aryLine = strLine.Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = ; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
dt.Columns.Add(dc);
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = ; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
} sr.Close();
fs.Close();
return dt;
}
public static void DataTableToCSV(DataTable dt, string fullPath)//table数据写入csv
{
System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
string data = ""; for (int i = ; i < dt.Columns.Count; i++)//写入列名
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - )
{
data += ",";
}
}
sw.WriteLine(data); for (int i = ; i < dt.Rows.Count; i++) //写入各行数据
{
data = "";
for (int j = ; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
} data += str;
if (j < dt.Columns.Count - )
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = ;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > )
{
workbook = new XSSFWorkbook(fs);
}
// 2003版本
else if (filePath.IndexOf(".xls") > )
{
workbook = new HSSFWorkbook(fs);
} if (workbook != null)
{
sheet = workbook.GetSheetAt();//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > )
{
IRow firstRow = sheet.GetRow();//第一行
int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列
if (isColumnName)
{
startRow = ;//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + ));
dataTable.Columns.Add(column);
}
} //填充行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue; dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == || format == || format == || format == )
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
return dataTable;
}
catch (Exception)
{
if (fs != null)
{
fs.Close();
}
return null;
}
}
public static DataSet ExcelToDataSet(string filePath, out string strMsg)
{
strMsg = "";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string fileType = Path.GetExtension(filePath).ToLower();
string fileName = Path.GetFileName(filePath).ToLower();
try
{
ISheet sheet = null;
int sheetNumber = ;
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
if (fileType == ".xlsx")
{
// 2007版本
XSSFWorkbook workbook = new XSSFWorkbook(fs);
sheetNumber = workbook.NumberOfSheets;
for (int i = ; i < sheetNumber; i++)
{
string sheetName = workbook.GetSheetName(i);
sheet = workbook.GetSheet(sheetName);
if (sheet != null)
{
dt = GetSheetDataTable(sheet, out strMsg);
if (dt != null)
{
dt.TableName = sheetName.Trim();
ds.Tables.Add(dt);
}
else
{
// MessageBox.Show("Sheet数据获取失败,原因:" + strMsg);
}
}
}
}
else if (fileType == ".xls")
{
// 2003版本
HSSFWorkbook workbook = new HSSFWorkbook(fs);
sheetNumber = workbook.NumberOfSheets;
for (int i = ; i < sheetNumber; i++)
{
string sheetName = workbook.GetSheetName(i);
sheet = workbook.GetSheet(sheetName);
if (sheet != null)
{
dt = GetSheetDataTable(sheet, out strMsg);
if (dt != null)
{
dt.TableName = sheetName.Trim();
ds.Tables.Add(dt);
}
else
{
//MessageBox.Show("Sheet数据获取失败,原因:" + strMsg);
}
}
}
}
return ds;
}
catch (Exception ex)
{
strMsg = ex.Message;
return null;
}
}
public static bool DataTableToExcel(DataTable dt,string Path)
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
try
{
if (dt != null && dt.Rows.Count > )
{
if (Path.IndexOf(".xlsx") > )
{
workbook = new XSSFWorkbook();
}
// 2003版本
else if (Path.IndexOf(".xls") > )
{
workbook = new HSSFWorkbook();
} sheet = workbook.CreateSheet("Sheet1");//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //设置列头
row = sheet.CreateRow();//excel第一行设为列头
for (int c = ; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
} //设置每行每列的单元格,
for (int i = ; i < rowCount; i++)
{
row = sheet.CreateRow(i + );
for (int j = ; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行开始写入数据
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(Path))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
result = true;
}
}
return result;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
public static void DataTableToPDF(DataTable dtSource, string localFilePath, string HorV)
{
//iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsian.dll");
//iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsianCmaps.dll");
BaseFont bf;
//string basepath = Application.StartupPath;
string basepath = @"C:\\WINDOWS\";
try {
bf = BaseFont.CreateFont(basepath + "\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
catch {
bf = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
iTextSharp.text.Font font = new iTextSharp.text.Font(bf);
iTextSharp.text.Document pdf;
if (string.IsNullOrEmpty(HorV))
pdf = new iTextSharp.text.Document();
else pdf = new iTextSharp.text.Document(PageSize.A4.Rotate());
PdfPTable table = new PdfPTable(dtSource.Columns.Count);
table.HorizontalAlignment = Element.ALIGN_CENTER;
PdfPCell cell;
for (int i = ; i < dtSource.Rows.Count + ; i++)
{
for (int j = ; j < dtSource.Columns.Count; j++)
{
if (i == )
{
cell = new PdfPCell(new Phrase(dtSource.Columns[j].ColumnName, font));
}
else
{
cell = new PdfPCell(new Phrase(dtSource.Rows[i - ][j].ToString(), font));
}
table.AddCell(cell);
}
}
using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
{
PdfWriter.GetInstance(pdf, fs);
pdf.Open();
pdf.Add(table);
pdf.Close();
}
} /// <summary>
/// 获取sheet表对应的DataTable
/// </summary>
/// <param name="sheet">Excel工作表</param>
/// <param name="strMsg"></param>
/// <returns></returns>
private static DataTable GetSheetDataTable(ISheet sheet, out string strMsg)
{
strMsg = "";
DataTable dt = new DataTable();
string sheetName = sheet.SheetName;
int startIndex = ;// sheet.FirstRowNum;
int lastIndex = sheet.LastRowNum;
//最大列数
int cellCount = ;
IRow maxRow = sheet.GetRow();
for (int i = startIndex; i <= lastIndex; i++)
{
IRow row = sheet.GetRow(i);
if (row != null && cellCount < row.LastCellNum)
{
cellCount = row.LastCellNum;
maxRow = row;
}
}
//列名设置
try
{
for (int i = ; i < maxRow.LastCellNum; i++)//maxRow.FirstCellNum
{
dt.Columns.Add(Convert.ToChar(((int)'A') + i).ToString());
//DataColumn column = new DataColumn("Column" + (i + 1).ToString());
//dt.Columns.Add(column);
}
}
catch
{
strMsg = "工作表" + sheetName + "中无数据";
return null;
}
//数据填充
for (int i = startIndex; i <= lastIndex; i++)
{
IRow row = sheet.GetRow(i);
DataRow drNew = dt.NewRow();
if (row != null)
{
for (int j = row.FirstCellNum; j < row.LastCellNum; ++j)
{
if (row.GetCell(j) != null)
{
ICell cell = row.GetCell(j);
switch (cell.CellType)
{
case CellType.Blank:
drNew[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == || format == || format == || format == )
drNew[j] = cell.DateCellValue;
else
drNew[j] = cell.NumericCellValue;
if (cell.CellStyle.DataFormat == || cell.CellStyle.DataFormat == || cell.CellStyle.DataFormat == )
drNew[j] = cell.NumericCellValue.ToString("#0.00");
break;
case CellType.String:
drNew[j] = cell.StringCellValue;
break;
case CellType.Formula:
try
{
drNew[j] = cell.NumericCellValue;
if (cell.CellStyle.DataFormat == || cell.CellStyle.DataFormat == || cell.CellStyle.DataFormat == )
drNew[j] = cell.NumericCellValue.ToString("#0.00");
}
catch
{
try
{
drNew[j] = cell.StringCellValue;
}
catch { }
}
break;
default:
drNew[j] = cell.StringCellValue;
break;
}
}
}
}
dt.Rows.Add(drNew);
}
return dt;
} }
}
C#-FileHelper的更多相关文章
- 【无私分享:ASP.NET CORE 项目实战(第七章)】文件操作 FileHelper
目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 在程序设计中,我们很多情况下,会用到对文件的操作,在 上一个系列 中,我们有很多文件基本操作的示例,在Core中有一些改变,主 ...
- C# 最全的文件工具类FileHelper
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...
- [No0000DC]C# FileHelper 本地文件、文件夹操作类封装FileHelper
using System; using System.Diagnostics; using System.IO; using System.Text; using Shared; namespace ...
- FileHelper
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Win ...
- 免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)
很多的软件项目中都会使用到定时任务.定时轮询数据库同步,定时邮件通知等功能..NET Framework具有“内置”定时器功能,通过System.Timers.Timer类.在使用Timer类需要面对 ...
- sqlyog导出json数据格式支持mysql数据转存mongodb
<!-------------知识的力量是无限的(当然肯定还有更简单的方法)-----------!> 当我考虑将省市区三级联动数据从mysql转入mongodb时遇到了网上无直接插入mo ...
- 【无私分享:ASP.NET CORE 项目实战】目录索引
简介 首先,我们的 [无私分享:从入门到精通ASP.NET MVC] 系列已经接近尾声,希望大家在这个过程中学到了一些思路和方法,而不仅仅是源码. 因为是第一次写博客,我感觉还是比较混乱的,其中 ...
- shell 带签名请求,yii 处理带签名的请求
处理请求 class TestController extends Controller { public function init() { if(!YII_ENV_DEV){ throw new ...
- Thread.Sleep引发ThreadAbortException异常
短信平台记录日志模块,是通过异步方式来记录的,即日志工具类里初始化一个Queue对象,公共的写日志方法的处理逻辑是把日志消息放到Queue里.构造器里设定一个死循环,不停的读队,然后把日志消息持久化到 ...
随机推荐
- 报错:Error, CM server guid updated, expected xxxxx, received xxxxx (未解决)
报错背景: CDH断电重启后,cloudera-scm-server启动报错, cloudera-scm-server 已死,但 pid 文件仍存 由于没有成熟的解决方案,于是我就重新安装了MySQL ...
- DEBUG技巧里的问题1 双击某个变量不能显示
DEBUG模式 双击 ls_return-type 变量不能显示,提示警告消息 好像说明的不是这个问题, 把字段复制到右边的变量框里可以显示 这个确实有点奇怪了
- 使用SoapUI测试wsdl
webservice服务wsdl地址:http://localhost:8080/services/HelloWorld?wsdl new project: new soap project: 调用测 ...
- Python - Django - 模板语言之变量
前言: 在 Django 模板语言中变量用 {{ }},逻辑用 {% %} 在 urls.py 中添加对应关系 from django.conf.urls import url from django ...
- 正则表达式入门教程&&经典Javascript正则表达式
前言 例子: ^.+@.+\\..+$ 这样的代码曾经多次把我自己给吓退过.可能很多人也是被这样的代码给吓跑的吧.继续阅读本文将让你也可以自由应用这样的代码. 正文 教程:正则表达式30分钟入门教程 ...
- Linux终极shell-zsh的完美配置方案!——oh-my-zsh
Zsh 介绍 Zsh 兼容 Bash,据传说 99% 的 Bash 操作 和 Zsh 是相同的 Zsh 官网:http://www.zsh.org/ 先看下你的 Linux支持哪些 shell:cat ...
- 【网络开发】UDP组播接收端解析
UDP组播接收端解析 网络中的一台主机如果希望能够接收到来自网络中其它主机发往某一个组播组的数据报,那么这么主机必须先加入该组播组,然后就可以从组地址接收数据包.在广域网中,还涉及到路由器支持组播路由 ...
- linux 软连接【转】
https://www.cnblogs.com/kex1n/p/5193826.html这是linux中一个非常重要命令,请大家一定要熟悉.它的功能是为某一个文件在另外一个位置建立一个同不的链接,这个 ...
- linux中matlab的中文乱码问题
ref:http://hi.baidu.com/36470902/item/47f3b133c419d989f5e4ade1 将系统的jre拷贝到matlab去 . sudo mv $MATLAB/s ...
- Linux将.deb以绿色免安装的方式“安装”
1.如果是xxx.deb文件,一般网上都是教你dkpg -i xxx.deb,但是这种方式类似windows里的安装,可能会在很多地方生成一些“垃圾”数据[比如不需要在dpkg安装应用信息文件里写入此 ...