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 = 0; intLine < arrayList.Count; intLine++) { arrDN = arrayList[intLine].ToString().Split(new char[] { ' ' }); if (intLine == 0) // Add Colunm { for (int m = 0; 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 = 0; i < dt.Columns.Count; i++) { if (i > 0) { str += " "; } str += dt.Columns[i].ColumnName; } sw.WriteLine(str); //写内容 for (int rowNo = 0; rowNo < dt.Rows.Count; rowNo++) { String tempstr = " "; for (int columnNo = 0; columnNo < dt.Columns.Count; columnNo++) { if (columnNo > 0) { tempstr += " "; } //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 = 0; //标示是否是读取的第一行 bool IsFirst = true; //逐行读取CSV中的数据 while ((strLine = sr.ReadLine()) != null) { aryLine = strLine.Split(','); if (IsFirst == true) { IsFirst = false; columnCount = aryLine.Length; //创建列 for (int i = 0; i < columnCount; i++) { DataColumn dc = new DataColumn(aryLine[i]); dt.Columns.Add(dc); } } else { DataRow dr = dt.NewRow(); for (int j = 0; 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 = 0; i < dt.Columns.Count; i++)//写入列名 { data += dt.Columns[i].ColumnName.ToString(); if (i < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); for (int i = 0; i < dt.Rows.Count; i++) //写入各行数据 { data = ""; for (int j = 0; j < dt.Columns.Count; j++) { string str = dt.Rows[i][j].ToString(); str = str.Replace(""", """");//替换英文冒号 英文冒号需要换成两个冒号 if (str.Contains(',') || str.Contains('"') || str.Contains(' ') || str.Contains(' ')) //含逗号 冒号 换行符的需要放到引号中 { str = string.Format(""{0}"", str); } data += str; if (j < dt.Columns.Count - 1) { 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 = 0; try { using (fs = File.OpenRead(filePath)) { // 2007版本 if (filePath.IndexOf(".xlsx") > 0) { workbook = new XSSFWorkbook(fs); } // 2003版本 else if (filePath.IndexOf(".xls") > 0) { workbook = new HSSFWorkbook(fs); } if (workbook != null) { sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet dataTable = new DataTable(); if (sheet != null) { int rowCount = sheet.LastRowNum;//总行数 if (rowCount > 0) { IRow firstRow = sheet.GetRow(0);//第一行 int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列 if (isColumnName) { startRow = 1;//如果第一行是列名,则从第二行开始读取 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 + 1)); 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 == 14 || format == 31 || format == 57 || format == 58) 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 = 0; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); if (fileType == ".xlsx") { // 2007版本 XSSFWorkbook workbook = new XSSFWorkbook(fs); sheetNumber = workbook.NumberOfSheets; for (int i = 0; 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 = 0; 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 > 0) { if (Path.IndexOf(".xlsx") > 0) { workbook = new XSSFWorkbook(); } // 2003版本 else if (Path.IndexOf(".xls") > 0) { workbook = new HSSFWorkbook(); } sheet = workbook.CreateSheet("Sheet1");//创建一个名称为Sheet0的表 int rowCount = dt.Rows.Count;//行数 int columnCount = dt.Columns.Count;//列数 //设置列头 row = sheet.CreateRow(0);//excel第一行设为列头 for (int c = 0; c < columnCount; c++) { cell = row.CreateCell(c); cell.SetCellValue(dt.Columns[c].ColumnName); } //设置每行每列的单元格, for (int i = 0; i < rowCount; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; 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 = 0; i < dtSource.Rows.Count + 1; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { if (i == 0) { cell = new PdfPCell(new Phrase(dtSource.Columns[j].ColumnName, font)); } else { cell = new PdfPCell(new Phrase(dtSource.Rows[i - 1][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 = 0;// sheet.FirstRowNum; int lastIndex = sheet.LastRowNum; //最大列数 int cellCount = 0; IRow maxRow = sheet.GetRow(0); 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 = 0; 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 == 14 || format == 31 || format == 57 || format == 58) drNew[j] = cell.DateCellValue; else drNew[j] = cell.NumericCellValue; if (cell.CellStyle.DataFormat == 177 || cell.CellStyle.DataFormat == 178 || cell.CellStyle.DataFormat == 188) 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 == 177 || cell.CellStyle.DataFormat == 178 || cell.CellStyle.DataFormat == 188) 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; } } }