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两种判断,表明了这其实是一个二分类问题 我们又知道回归就 ...
随机推荐
- Codeigniter-验证数据类
个人需求,仿着CI的表单验证写了一个自己的验证类 1.定义验证类 <?php if ( ! defined('BASEPATH')) exit('No direct script access ...
- 移动端消除click事件的延迟效果
https://github.com/Plaputta/jquery.event.special.fastclick 用fastclick事件,类似zepto的tap事件,若想去除连点效果,可在外层显 ...
- 12个Icon图标资源网站
1.除了Icon以外,还有很多不错的UI设计素材. 地址:http://worldui.com/2.除了免费Icon资源下载以外,还提供Icon定制的付费服务.地址:http://dryicons.c ...
- 学学Whatsapp,如何让自己挣160亿美金,然后退休?开发个J2ME应用。
facebook用160亿美元收购了Whatsapp,要知道这是facebook市值1600亿美元的十分之一,而Whatsapp是一个只有50名员工的小公司,这个价格让硅谷各种科技公司大佬跌破镜框.其 ...
- windows通过Composer安装yii2
1. php.ini 中;extension=php_openssl.dll(取消注释,不然在安装composer过程中会报错) 集成环境最好去php目录中打开php.ini文件,确定;extensi ...
- 2016030205 - ubuntu安装mysql
ubuntu上安装mysql 1.检查ubuntu上是否已经安装mysql sudo netstat -tap | grep mysql 本机上没有安装mysql 2.安装mysql服务器端和客户端 ...
- adb的logcat使用
预备:安装刷机精灵,实用工具->adb命令行 1. 对于多机设备,首先使用adb devices来获知设备名称: 2. 将log输出到电脑:adb –s [设备名称] shell logcat ...
- oc调用c++接口时 报错 Undefined symbols for architecture i386:
当在oc中调用c++中的方法时,发现说c++中的方法没定义或是找不到 Undefined symbols for architecture i386: "_desTYData", ...
- RSA算法原理(一)
如果你问我,哪一种算法最重要? 我可能会回答"公钥加密算法". 因为它是计算机通信安全的基石,保证了加密数据不会被破解.你可以想象一下,信用卡交易被破解的后果. 进入正题之前,我先 ...
- 【HDOJ】2389 Rain on your Parade
读题显然是二分图匹配,看成guest与umbrella的匹配.匈牙利果断TLE了,其实时间卡的相当紧.HK过的,750ms. /* 2389 */ #include <iostream> ...