using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data;
using System.IO;
using System.Data.OleDb;
using Aspose.Cells; namespace Common
{
public class CSV
{
/// <summary>
/// "HDR=Yes;"声名第一行的数据为域名,并非数据。
/// 这种方式读取csv文件前8条为int类型后面为string类型 则后面数据读取不了
/// 还存在乱码问题
/// </summary>
/// <param name="fullPath"></param>
/// <returns></returns>
public static DataTable Read(string fullPath)
{
FileInfo fileInfo = new FileInfo(fullPath);
DataTable table = new DataTable();
string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileInfo.DirectoryName + ";Extended Properties='Text;HDR=YES;FMT=Delimited;IMEX=1;'";
string cmdstring = String.Format("select * from [{0}]", fileInfo.Name); using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open(); OleDbDataAdapter adapter = new OleDbDataAdapter(cmdstring, conn);
adapter.Fill(table); conn.Close();
} return table;
} public static List<string> Read2(string fullpath)
{
DataTable table = CSV.Read(fullpath);
List<string> records = new List<string>(); foreach (DataRow row in table.Rows)
{
records.Add(row[].ToString());
} return records;
} public static string ExportToCSV(DataTable table)
{
StringBuilder sb = new StringBuilder(); for (int i = ; i < table.Columns.Count; i++)
{
if (i == table.Columns.Count - )
{
sb.Append(table.Columns[i].Caption);
}
else
{
sb.AppendFormat("{0},", table.Columns[i].Caption);
}
}
sb.Append(Environment.NewLine); for (int index = ; index < table.Rows.Count; index++)
{
StringBuilder sb2 = new StringBuilder();
DataRow row = table.Rows[index]; for (int i = ; i < table.Columns.Count; i++)
{ string input = row[i].ToString();
string format = "{0}";
if (input.Contains(","))
{
format = "\"{0}\"";
} if (i == table.Columns.Count - )
{
sb.Append(String.Format(format, ReplaceSpecialChars(input)));
}
else
{
sb.AppendFormat(format + ",", ReplaceSpecialChars(input));
}
} if (index < table.Rows.Count - )
sb.Append(Environment.NewLine);
} return sb.ToString();
} public static void ExportToCSVFile(DataTable table, string filename)
{
// using (StreamWriter sw = new StreamWriter(filename, false,Encoding.UTF8))
using (StreamWriter sw = new StreamWriter(filename, false))
{
string text = ExportToCSV(table);
sw.WriteLine(text);
}
} public static string ReplaceSpecialChars(string input)
{
// space -> _x0020_ 特殊字符的替换
// % -> _x0025_
// # -> _x0023_
// & -> _x0026_
// / -> _x002F_
if (input == null)
return "";
//input = input.Replace(" ", "_x0020_");
//input.Replace("%", "_x0025_");
//input.Replace("#", "_x0023_");
//input.Replace("&", "_x0026_");
//input.Replace("/", "_x002F_"); input = input.Replace("\"", "\"\""); return input;
} public static DataTable ReadExcel(string fullpath, string sheetname = "sheet1$")
{
DataTable table = new DataTable(); string connectionstring = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;';", fullpath);
//string cmdstring = "select * from [sheet1$]";
string cmdstring = "select * from [" + sheetname + "]"; using (OleDbConnection conn = new OleDbConnection(connectionstring))
{
conn.Open(); OleDbDataAdapter adapter = new OleDbDataAdapter(cmdstring, conn);
adapter.Fill(table); conn.Close();
} return table;
} public static DataTable ExcelDs(string filenameurl)
{
string strConn = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", filenameurl); ;
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
//返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等 
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包含excel中表名的字符串数组
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = ; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
} OleDbDataAdapter odda = new OleDbDataAdapter("select * from [" + strTableNames[] + "]", conn);
DataTable ds = new DataTable(); odda.Fill(ds); conn.Close();
conn.Dispose();
return ds;
} public static DataTable ReadExcelTopVersion(string fullpath, string sheetname = "sheet1$")
{
DataTable table = new DataTable(); //我测试用下
//string connectionstring = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;';", fullpath); //这个是正确的
string connectionstring = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", fullpath);
//string cmdstring = "select * from [sheet1$]";
string cmdstring = "select * from [" + sheetname + "]"; using (OleDbConnection conn = new OleDbConnection(connectionstring))
{
conn.Open(); OleDbDataAdapter adapter = new OleDbDataAdapter(cmdstring, conn);
adapter.Fill(table); conn.Close();
} return table;
} public static List<string> ReadExcel2(string fullpath)
{
List<string> records = new List<string>();
DataTable table = CSV.ReadExcel(fullpath); foreach (DataRow row in table.Rows)
{
records.Add(row[].ToString());
} return records;
} /// <summary>
/// 使用Aspose方法读取csv文件
/// 当前8条数据为int类型,后面数据为string类型,会报错
/// 乱码文件正确读取
/// </summary>
/// <param name="fullpath"></param>
/// <returns></returns>
public static DataTable ReadCSVByAspose(string fullpath)
{
Workbook workbook = new Workbook(fullpath);
Cells cells = workbook.Worksheets[].Cells;
DataTable data = cells.ExportDataTable(, , cells.MaxDataRow, cells.MaxDataColumn + , true);
return data;
} /// <summary>
/// sun : use ace.oledb, not use jet.oledb
/// </summary>
/// <param name="excelFilename"></param>
/// <returns></returns>
public static DataTable ReadCSVByACEOLEDB(string excelFilename)
{
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"{0}\";Extended Properties=\"Text\"", Directory.GetParent(excelFilename));
DataSet ds = new DataSet();
string fileName = string.Empty;
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connectionString))
{
connection.Open();
fileName = Path.GetFileName(excelFilename); string strExcel = "select * from " + "[" + fileName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, connectionString);
adapter.Fill(ds, fileName);
connection.Close();
//tableNames.Clear();
}
return ds.Tables[fileName];
} }
}

备注: 需要安装引擎

服务器未安装office软件的时候,使用连接字符串,读取excel失败的解决办法,下载 安装即可

Microsoft Access Database Engine 2010 Redistributable

 

对应的excel连接字符串:

"Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";

常用类-CSV---OLEDB的更多相关文章

  1. Foundation框架下的常用类:NSNumber、NSDate、NSCalendar、NSDateFormatter、NSNull、NSKeyedArchiver

    ========================== Foundation框架下的常用类 ========================== 一.[NSNumber] [注]像int.float.c ...

  2. JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式

    相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...

  3. Java集合常用类特点整理

    集合的结构如下图所示: 集合的两个顶级接口分别为:Collection和Map Collection下有两个比较常用的接口分别是List(列表)和Set(集),其中List可以存储重复元素,元素是有序 ...

  4. Java集合框架(常用类) JCF

    Java集合框架(常用类) JCF 为了实现某一目的或功能而预先设计好一系列封装好的具有继承关系或实现关系类的接口: 集合的由来: 特点:元素类型可以不同,集合长度可变,空间不固定: 管理集合类和接口 ...

  5. java-API中的常用类,新特性之-泛型,高级For循环,可变参数

    API中的常用类 System类System类包含一些有用的类字段和方法.它不能被实例化.属性和方法都是静态的. out,标准输出,默认打印在控制台上.通过和PrintStream打印流中的方法组合构 ...

  6. Java基础复习笔记系列 五 常用类

    Java基础复习笔记系列之 常用类 1.String类介绍. 首先看类所属的包:java.lang.String类. 再看它的构造方法: 2. String s1 = “hello”: String ...

  7. iOS 杂笔-24(常用类到NSObject的继承列表)

    iOS 杂笔-24(常用类到NSObject的继承列表) NSString NSObject->NSString NSArray NSObject->NSArray ↑OC基本类都直接继承 ...

  8. java的eclipse操作和常用类Object的使用

    1.eclipse的快捷键: (1)alt + /   内容辅助. 如:main+alt + / 会出现完整的main方法. syso+alt+ / 会输出. 如编写某个方法时,只需写入方法名 + a ...

  9. java总结第四次//常用类

    六.常用类 主要内容:Object类.String类.Date类.封装类 (一)Object类 1.Object类是所有Java类的根父类 2.如果在类的声明中未使用extends关键字指明其父类,则 ...

  10. JAVA基础知识之IO——Java IO体系及常用类

    Java IO体系 个人觉得可以用"字节流操作类和字符流操作类组成了Java IO体系"来高度概括Java IO体系. 借用几张网络图片来说明(图片来自 http://blog.c ...

随机推荐

  1. Django之视图层与模板层

    目录 视图层 小白必会三板斧 HttpResponse render redirect JsonResponse 前后端分离 FBV CBV 给CBV加装饰器 模板层 模板语法 模板传值 过滤器 语法 ...

  2. 格式化字符串漏洞 format string exploit(一)

    本文系原创,转载请说明出处 本文为基于CTF WIKI的PWN学习 0x00 格式化字符串原理 先附一张经典的图,如下 其栈上布局如下: some value 3.14 123456 addr of ...

  3. 面试连环炮系列(十五):说说Eureka的高可用方案

    说说Eureka的高可用方案 至少3个Eureka实例才能满足高可用,配置方法如下: 准备三个节点node1,node2,node3. 在每个实例的application.xml文件里加入 eurek ...

  4. Dynamics 365中的Client API form context (formContext)

    适用于Dynamics 365 for Customer Engagement apps 9.x版本. 本文是一篇翻译,原文来源是微软官方文档. 本文链接:https://www.cnblogs.co ...

  5. [C]struct结构化数据的一些要点

    1.用typedef声明一个短语代替冗长的struct成员声明 int main(void) { typedef struct Hores Hores; struct Hores { int age; ...

  6. 如何判断一个变量是否为数组(isArray)

    在我们平时的工作中经常会用到如何判断一个变量是否为数组.常用的方法很多,有用常用框架里面的,isArray.但是关于这个isArray的实现,各有不同. 常用的方法有如下几种 1.instanceof ...

  7. MySQL数据库基础笔记

    数据库 数据库就是存储和管理数据的仓库,用户可以对数据库中的数据进行增删改查等操作. 数据库的分类 关系型数据库(Oracle.MySQL.SQLite等) 非关系型数据库(Redis.MongoDB ...

  8. 一起学SpringMVC之文件上传

    概述 在Web系统开发过程中,文件上传是普遍的功能,本文主要以一个简单的小例子,讲解SpringMVC中文件上传的使用方法,仅供学习分享使用,如有不足之处,还请指正. 文件上传依赖包 如下所示,文件上 ...

  9. pyhton的安装,环境变量的设置,pycharm的安装下载,中文汉化和字体的设置

    1.下载pycharm https://www.7down.com/soft/336988.html 1.pycharm的汉化下载汉化包:resources_cn.jar    放到pycharm的安 ...

  10. spark shell操作

    RDD有两种类型的操作 ,分别是Transformation(返回一个新的RDD)和Action(返回values). 1.Transformation:根据已有RDD创建新的RDD数据集build ...