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的更多相关文章

  1. 【无私分享:ASP.NET CORE 项目实战(第七章)】文件操作 FileHelper

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 在程序设计中,我们很多情况下,会用到对文件的操作,在 上一个系列 中,我们有很多文件基本操作的示例,在Core中有一些改变,主 ...

  2. C# 最全的文件工具类FileHelper

    using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...

  3. [No0000DC]C# FileHelper 本地文件、文件夹操作类封装FileHelper

    using System; using System.Diagnostics; using System.IO; using System.Text; using Shared; namespace ...

  4. FileHelper

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Win ...

  5. 免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)

    很多的软件项目中都会使用到定时任务.定时轮询数据库同步,定时邮件通知等功能..NET Framework具有“内置”定时器功能,通过System.Timers.Timer类.在使用Timer类需要面对 ...

  6. sqlyog导出json数据格式支持mysql数据转存mongodb

    <!-------------知识的力量是无限的(当然肯定还有更简单的方法)-----------!> 当我考虑将省市区三级联动数据从mysql转入mongodb时遇到了网上无直接插入mo ...

  7. 【无私分享:ASP.NET CORE 项目实战】目录索引

    简介 首先,我们的  [无私分享:从入门到精通ASP.NET MVC]   系列已经接近尾声,希望大家在这个过程中学到了一些思路和方法,而不仅仅是源码. 因为是第一次写博客,我感觉还是比较混乱的,其中 ...

  8. shell 带签名请求,yii 处理带签名的请求

    处理请求 class TestController extends Controller { public function init() { if(!YII_ENV_DEV){ throw new ...

  9. Thread.Sleep引发ThreadAbortException异常

    短信平台记录日志模块,是通过异步方式来记录的,即日志工具类里初始化一个Queue对象,公共的写日志方法的处理逻辑是把日志消息放到Queue里.构造器里设定一个死循环,不停的读队,然后把日志消息持久化到 ...

随机推荐

  1. Django之Restful API

    理解Restful架构:http://www.ruanyifeng.com/blog/2011/09/restful RESTful设计指南:http://www.ruanyifeng.com/blo ...

  2. js文档系统-jsdoc-docdash

    一.参考文档 模版:https://github.com/clenemt/docdash 例子:http://clenemt.github.io/docdash/index.html jsdoc:ht ...

  3. QuickTime专业版 pro 注册码

    打开QuickTime Player下拉编辑菜单--选偏好设置--注册 Name: Dawn M Fredette Key: 4UJ2-5NLF-HFFA-9JW3-X2KV 重新启动 QuickTi ...

  4. <automate the boring stuff with python> 正则强口令实例

    书中7.18的强口令实践题 写一个函数,它使用正则表达式,确保传入的口令字符串是强口令.强口令的定义是: 长度不少于8 个字符,同时包含大写和小写字符,至少有一位数字. 你可能需要用多个正则表达式来测 ...

  5. Stream知识点总结及源码阅读

    上次[http://www.cnblogs.com/webor2006/p/7795596.html]对Stream进行了简单的学习,这次继续学习Stream,还是结合java8 in action这 ...

  6. python基础学习(八)

    17.嵌套循环 # 嵌套循环 nested loop # 在一个循环中使用另外一个循环 num_list1 = [1, 2, 3, 4] num_list2 = [6, 7, 8, 9] # 组合li ...

  7. python 之 并发编程(开启子进程的两种方式,进程对象的属性)

    第九章并发编程 同一个程序执行多次是多个进程 import time import os ​ print('爹是:',os.getppid()) #父进程PID,(pycharm) print('me ...

  8. ps 指令

    ps显示系统当前进程信息, ps 存在多个版本,因此 ps options 的种类繁多.这里只列举平时开发过程中常用的命令,如果有错误或者更好的例子.烦请在评论区指出 语法 ps [options] ...

  9. 【springcloud】1.微服务之springcloud-》eureka源码分析之请叫我灵魂画师。。。

  10. ALV报表——ALV颜色设置(三)

    目录 一.行 二.列 三.单元格 四.附ALV的颜色代码 一.行:用Layout相关属性设置 代码: *Report ZRFI001_XFL_TEST REPORT ZRFI001_XFL_TEST ...