DataFromFile
#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的更多相关文章
- 02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器
[day0201_NSFileHandle]:文件句柄 1 NSFileHandle 文件对接器.文件句柄 常用API: - (NSData *)readDataToEndOfFile;读取数据到最后 ...
- Go Web:处理请求
处理请求 Request和Response http Requset和Response的内容包括以下几项: Request or response line Zero or more headers ...
- 基于LumiSoft.Net.dll发、收、删邮件
发邮件: using LumiSoft.Net.SMTP.Client; Mime m = new Mime(); MimeEntity mainEntity = m.MainEntity; // F ...
- 【4】Logistic回归
前言 logistic回归的主要思想:根据现有数据对分类边界建立回归公式,以此进行分类 所谓logistic,无非就是True or False两种判断,表明了这其实是一个二分类问题 我们又知道回归就 ...
随机推荐
- 发现一款移动web端远程调试工具weinre , 哈哈!
之前调试一直用的是chrome的远程调试,虽然效果很不错,但是在调试cordova,微信时多有不便. 在git上找工具时发现了这个:weinre,使用方法非常简单 附上git地址: https://g ...
- fedora安装sublime text教程
下载 http://pan.baidu.com/s/1eRkEegM 解压 终端中切换到下载文件的目录下,执行以下命令: sudo tar -jxvf sublime_text_3_build_308 ...
- ThinkPHP Uploadify 图片上载
从官方网站下载的Uploadify最新版本:http://www.uploadify.com/download/ jQuery库是1.7.1版本. 下载好的Uploadify目录下面的文件有: 用到的 ...
- Linux运维需要掌握的技能 (转)
本人是linux运维工程师,对这方面有点心得,现在我说说要掌握哪方面的工具吧说到工具,在行外可以说是技能,在行内我们一般称为工具,就是运维必须要掌握的工具.我就大概列出这几方面,这样入门就基本没问题了 ...
- iOS: 布局可视化语法 Visual Format Syntax
可视化语法 Visual Format Syntax The following are examples of constraints you can specify using the visua ...
- C语言笔记(二维数组与数值指针)
一.关于二维数组和二维数组区别 (1)一维数组在内存中是连续分布存储的,同样,二维数组也是在内存连续存储的.所以从内存的角度来分析,一维数组和二维数组其实没有本质区别. (2) 二维数组可以使用一维数 ...
- bzoj2011: [Ceoi2010]Mp3 Player
Description Georg有个MP3 Player,没有任何操作T秒钟就会锁定,这时按下任意一个键就会变回没锁定的状态,但不会改变频道.只有在没锁定的状态下按键才有可能改变频道. MP3的频道 ...
- X/Open DTP——分布式事务模型
转载:http://www.cnblogs.com/aigongsi/archive/2012/10/11/2718313.html 这一几天一直在回顾事务相关的知识,也准备把以前了解皮毛的知识进行一 ...
- android ListView 多次调用 getView方法
<ListView android:layout_width="match_parent" android:layout_heig ...
- 【POJ1330】Nearest Common Ancestors(树链剖分求LCA)
Description A rooted tree is a well-known data structure in computer science and engineering. An exa ...