#region Copyright 2013, Andreas Hoffmann
// project location ==> http://datafromfile.codeplex.com/
#region License
/*
New BSD License (BSD) Copyright (c) 2013, Andreas Hoffmann
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
#endregion using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet; namespace Ipxxl.Data
{
/// <summary>
///
/// </summary>
public sealed class DataFromFile
{
/// <summary>
/// This function returns a DataTable for an Excel-file and the given parameters
/// </summary>
/// <param name="fileName">Name of file to be loaded (e.g. "sample.xls" or "sample.xlsx")</param>
/// <param name="hasHeaders">Headers in first row of Excel sheet?</param>
/// <returns>System.Data.DataTable</returns>
public static DataTable GetDataTableFromExcel(string fileName, bool hasHeaders)
{
if (File.Exists(fileName))
{
var hdr = hasHeaders ? "Yes" : "No";
var strConn = string.Empty;
var extension = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
switch (extension)
{
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Extended Properties=\"Excel 12.0 Macro;HDR=" + hdr + ";IMEX=1\"";
break;
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName +
";Extended Properties=\"Excel 8.0;HDR=" + hdr +
";IMEX=1\"";
break;
}
var output = new DataSet();
using (var conn = new OleDbConnection(strConn))
{
conn.Open();
var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
if (schemaTable != null)
foreach (
var tableName in
schemaTable.Rows.Cast<DataRow>()
.Select(schemaRow => schemaRow["TABLE_NAME"].ToString())
.Where(
tableName =>
tableName.LastIndexOf("'", StringComparison.Ordinal) >=
tableName.Length - )
)
{
try
{
var cmd = new OleDbCommand("SELECT * FROM [" + tableName + "]", conn)
{
CommandType = CommandType.Text
};
new OleDbDataAdapter(cmd).Fill(output,
tableName.Replace("$", string.Empty)
.Replace("'", string.Empty));
}
catch (Exception ex)
{
throw new Exception(
ex.Message + "Sheet:" + tableName.Replace("$", string.Empty) + ".File:" + fileName, ex);
}
}
conn.Close();
}
return output.Tables[];
}
throw new FileNotFoundException();
} /// <summary>
/// This function returns a DataTable for a CSV-file and the given parameters
/// </summary>
/// <param name="fileName">Name of file to be loaded (e.g. "sample.csv")</param>
/// <param name="delimiter">The delimiter char by which the fields are separated (e.g. ";")</param>
/// <param name="fileEncoding">The file encoding</param>
/// <param name="hasHeaders">Headers in first line of file?</param>
/// <returns>System.Data.DataTable</returns>
public static DataTable GetDataTableFromCsv(string fileName, char delimiter, Encoding fileEncoding,
bool hasHeaders)
{
var table = new DataTable();
if (File.Exists(fileName))
{
using (var reader = new StreamReader(fileName, fileEncoding))
{
var rowCounter = ;
while (true)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
if (line.Substring(line.Length - , ).Equals(delimiter.ToString()))
{
line = line.Substring(, line.Length - );
}
var parts = line.Split(delimiter);
if (rowCounter == && hasHeaders)
{
table = CreateDataTableHeaders(parts);
}
else
{
table.Rows.Add(parts);
}
rowCounter++;
}
}
return table;
}
throw new FileNotFoundException();
} /// <summary>
/// This function returns a DataTable for a XML-file
/// </summary>
/// <param name="fileName">Name of file to be loaded (e.g. "sample.xml")</param>
/// <returns>System.Data.DataTable</returns>
public static DataTable GetDataTableFromXml(string fileName)
{
var table = new DataTable();
if (File.Exists(fileName))
{
table.ReadXml(fileName);
return table;
}
throw new FileNotFoundException();
} /// <summary>
/// Writes the content of the given DataTable to a Xml-file
/// </summary>
/// <param name="dataTable">DataTable with content to write</param>
/// <param name="fileName">Filename for output file</param>
public static void WriteDataTableToXml(DataTable dataTable, string fileName)
{
dataTable.WriteXml(fileName, XmlWriteMode.IgnoreSchema);
} /// <summary>
/// Writes the content from the given DataTable to a CSV-File
/// </summary>
/// <param name="table">DataTable with Content to write</param>
/// <param name="fileName">Filename for output file</param>
/// <param name="encoding">Encoding of output file</param>
/// <param name="delimiter">A single char which delimits the fields</param>
/// <param name="withHeaders">true => the first row in output file will contain the ColumnNames from given DataTable</param>
public static void WriteDataTableToCsv(DataTable table, string fileName, Encoding encoding, char delimiter, bool withHeaders)
{
using (var writer = new StreamWriter(fileName, false, encoding))
{
if (withHeaders)
{
var headers = new StringBuilder();
foreach (DataColumn column in table.Columns)
{
headers.Append(column.ColumnName);
headers.Append(delimiter);
}
writer.WriteLine(headers.ToString());
}
foreach (DataRow row in table.Rows)
{
var rowdata = new StringBuilder();
foreach (var o in row.ItemArray)
{
rowdata.Append(o);
rowdata.Append(delimiter);
}
writer.WriteLine(rowdata.ToString());
}
}
} private static DataTable CreateDataTableHeaders(IEnumerable<string> parts)
{
var table = new DataTable();
foreach (var part in parts.Where(part => !string.IsNullOrEmpty(part)))
{
table.Columns.Add(part.Trim());
}
return table;
} /// <summary>
/// Writes the content from the given DataTable to a Excel-File (OpenXML-Format "xlsx")
/// </summary>
/// <param name="table">DataTable with Content to write</param>
/// <param name="fileName">Filename for output file</param>
/// <param name="withHeaders">true => the first row in output file will contain the ColumnNames from given DataTable</param>
public static void WriteDataTableToExcel2007(DataTable table, string fileName, bool withHeaders)
{
ExcelDocument doc = new ExcelDocument();
doc.CreatePackage(fileName);
//populate the data into the spreadsheet
using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(fileName, true))
{
WorkbookPart workbook = spreadsheet.WorkbookPart;
//create a reference to Sheet1
WorksheetPart worksheet = workbook.WorksheetParts.Last();
SheetData data = worksheet.Worksheet.GetFirstChild<SheetData>(); if (withHeaders)
{
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32) ; foreach (DataColumn column in table.Columns)
{
Cell headerCell = createTextCell(table.Columns.IndexOf(column) + , , column.ColumnName);
header.AppendChild(headerCell);
}
data.AppendChild(header);
}
//loop through each data row
DataRow contentRow;
for (int i = ; i < table.Rows.Count; i++)
{
contentRow = table.Rows[i];
data.AppendChild(createContentRow(contentRow, i + ));
}
}
} private static Cell createTextCell(int columnIndex, int rowIndex, object cellValue)
{
Cell cell = new Cell(); cell.DataType = CellValues.InlineString;
cell.CellReference = getColumnName(columnIndex) + rowIndex; InlineString inlineString = new InlineString();
Text t = new Text(); t.Text = cellValue.ToString();
inlineString.AppendChild(t);
cell.AppendChild(inlineString); return cell;
} private static Row createContentRow(DataRow dataRow, int rowIndex)
{
Row row = new Row
{
RowIndex = (UInt32)rowIndex
}; for (int i = ; i < dataRow.Table.Columns.Count; i++)
{
Cell dataCell = createTextCell(i + , rowIndex, dataRow[i]);
row.AppendChild(dataCell);
}
return row;
} private static string getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier; while (dividend > )
{
modifier = (dividend - ) % ;
columnName =
Convert.ToChar( + modifier).ToString() + columnName;
dividend = (int)((dividend - modifier) / );
} return columnName;
} }
}

DataFromFile的更多相关文章

  1. 02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器

    [day0201_NSFileHandle]:文件句柄 1 NSFileHandle 文件对接器.文件句柄 常用API: - (NSData *)readDataToEndOfFile;读取数据到最后 ...

  2. Go Web:处理请求

    处理请求 Request和Response http Requset和Response的内容包括以下几项: Request or response line Zero or more headers ...

  3. 基于LumiSoft.Net.dll发、收、删邮件

    发邮件: using LumiSoft.Net.SMTP.Client; Mime m = new Mime(); MimeEntity mainEntity = m.MainEntity; // F ...

  4. 【4】Logistic回归

    前言 logistic回归的主要思想:根据现有数据对分类边界建立回归公式,以此进行分类 所谓logistic,无非就是True or False两种判断,表明了这其实是一个二分类问题 我们又知道回归就 ...

随机推荐

  1. 一个简单的Hibernate工具类HibernateUtil

    HibernateUtil package com.wj.app.util; import org.hibernate.Session; import org.hibernate.SessionFac ...

  2. Ubuntu 误改/etc/sudoers 文件权限

    添加用户时不小心修改了/etc/sudoers 权限,结果不能sudo了,Ubuntu默认关闭root帐户,结果傻X了,无法改回了. 方法如下: 1.重启机器,开机按ESC,进入恢复模式 2.此时,磁 ...

  3. 区分html与css中的属性

    CSS中id与Class的区别 1.在CSS文件里书写时,ID加前缀"#":CLASS用"." 2.id一个页面只可以使用一次:class可以多次引用. 3.I ...

  4. 关于如何设置reduce的个数

    在默认情况下,一个MapReduce Job如果不设置Reducer的个数,那么Reducer的个数为1.具体,可以通过JobConf.setNumReduceTasks(int numOfReduc ...

  5. Contest20140906 ProblemC 菲波拉契数制 DP

    C.菲波拉契数制时间:2s   内存:65536KB我们定义如下数列为菲波拉契数列:                    F (1) = 1                    F (2) = 2 ...

  6. Contest20140705 testB DP

    testB 输入文件: testB.in 输出文件testB.out 时限2000ms 问题描述: 方师傅有两个由数字组成的串 a1,a2,⋯,an 和 b1,b2,⋯,bm.有一天,方师傅感到十分无 ...

  7. Codeforces 161D

    树形DP: 要求找出树上距离为k的点的对数: 对于每个节点,经过这个节点的符合条件的的点有两种: 第一种:距离他为i的儿子和他爸爸中距离他爸爸为k-i-1:(不是符合的点对中的一个) 第二种:他儿子中 ...

  8. sublime配置python开发

    想在sublime里要python shell那种交互或者run module F5 F5 F5下这种效果的话,还是挺容易实现的,windows下的:1. 打开Sublime text 3 安装pac ...

  9. Git入门简介

    ​1. Git 背景 Git 最初由Linus Torvalds编写,用于 Linux 内核开发的版本控制工具. Git 与常用的版本控制工具 CVS.Subversion 等不同,它采用了分布式版本 ...

  10. 创建range分区

    drop table T_PM_ACCT_DTL_AF_TEST; create table T_PM_ACCT_DTL_AF_TEST  (    DATA_DATE     date,    AC ...