#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. new作为修饰符

    new 修饰符与 new 操作符是两个概念 new 修饰符用于声明类或类的成员,表示隐藏了基类中同名的成员.而new 操作符用于实例化一个类型 new 修饰符只能用于继承类,一般用于弥补基类设计的不足 ...

  2. PHPCMS标签:PC标签模板语法规则

    模板语法规则1.变量表示{$name} 被解析成 <?=$name?>,表示显示变量$name的值,其中的“name”由英文字母.数字和下划线组成首字母必须是英文字母或者下划线. 2.常量 ...

  3. Django如何设置proxy

    设置porxy的原因 一般情况下我们代理设置是针对与浏览器而言,通常只需在浏览器设置中进行配置,但它只针对浏览器有效,对我们自己编写的程序并任何效果,这时就需要我们在软件编码中加入代理设置. --- ...

  4. Balanced Lineup

      Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 49061   Accepted: 22975 Case Time Lim ...

  5. codevs 1557 热浪

    传送门 题目描述 Description 德克萨斯纯朴的民眾们这个夏天正在遭受巨大的热浪!!!他们的德克萨斯长角牛吃起来不错,可是他们并不是很擅长生產富含奶油的乳製品.Farmer John此时以先天 ...

  6. data guard switchover切换异常

    data guard switchover切换异常 查看DG数据库备份库发现,switchover_status为SWITCHOVER LATENT SQL> select OPEN_MODE, ...

  7. iPhone手机VPN设置

    如果iPhone,iPad游戏或软件服务器在国外不能用,就需要设置VPN了. 如果是为了解除公司上网策略限制,或者为了上Google,Facebook,都可以通过设置VPN实现. 要使用VPN需要到V ...

  8. rm加转义很危险

    rm -r 想转义一个空格字符,转得不对 -r, -R, --recursive 递归删除目录及其内容 连续rm了n个不想rm的文件夹.%>_<% 想起来以前有人也因为rm的失误把整个wo ...

  9. 严重推荐一个免费开源数据库建模工具软件 --OpenSystemArchitect 4.0

    嘿嘿,对于我这样的新手,这个工具还是很令人兴奋的. 真的是术业有专攻啊.关键还是免费开源 EXCEL,VISO,PPT,PS,CD,FREEHAND不是不可以,只是.人家还是专业点,方便点.. Ope ...

  10. Git 、CVS、SVN比较

    Git .CVS.SVN比较 项目源代码的版本管理工具中,比较常用的主要有:CVS.SVN.Git 和 Mercurial  (其中,关于SVN,请参见我先前的博客:SVN常用命令 和 SVN服务器配 ...