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. express 中间件的简单应用与实现

    express 中间件的简单应用与实现 看了慕课网双越老师的课之后结合自己的理解做了一些简单的总结,如有不恰当之处,欢迎指正. 提到 express 就不得不提到中间件,接下来就简单的介绍一下 exp ...

  2. K8S命令-Kubectl 命令大全

    参考1:https://jimmysong.io/kubernetes-handbook/guide/kubectl-cheatsheet.html?h=kubectl Kubctl 命令是操作 ku ...

  3. springcloud 微服务分布式 框架源码 activiti工作流 前后分离

    1.代码生成器: [正反双向](单表.主表.明细表.树形表,快速开发利器)freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面.建表sql脚本.处理类.service等完整模块2. ...

  4. iOS开发 - 超级签名实现之描述文件

    简介 因为最近企业签掉得太严重了,上头要求实现超级签进行游戏下载.故有了此文章,记录一下过程. 签名原理其实很简单,超级签名的技术就是使用个人开发者账号,将用户的设备当作开发设备进行应用分发.这也导致 ...

  5. BIM工程信息管理系统搭建-系统功能需求

    BIM工程信息管理系统功能需求 该系统是真实存在项目,项目于2013年开始研发到2014年初完成,按照当时技术能力和国内BIM现状,现在BIM技术已比之前好多了,不管是建模.展示等.均提高了不少,本博 ...

  6. Linux CentOS 7 搭建 Tomcat 8 服务器

    Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选.对于一个初学者来说,可以这样 ...

  7. Windows Redis 安装(带视频)

    疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列 [博客园总入口 ] 架构师成长+面试必备之 高并发基础书籍 [Netty Zookeeper Redis 高并发实战 ] 疯狂创客圈 高并 ...

  8. Java 程序员最喜欢使用的日常工具

    多年来,Java 始终是企业应用程序的支柱.最近几年,Java 也是 Android 开发的首选编程语言.不过开发人员如何使用这种语言呢?一项新的研究阐明了主要使用 Java 的开发人员的工作类型,以 ...

  9. Splash 学习笔记

    一.介绍 Splash 跟之前我们介绍的 Selenium ( 参考 Selenium 与自动化测试 -- <Selenium 2 自动化测试实战>读书笔记) 很类似,都可以理解成一个浏览 ...

  10. Flutter - flutter desktop embedding / flutter 桌面支持

    2019年5月9日,随着谷歌在IO19宣布Flutter支持Web平台,就标志着Flutter已经全面支持所有平台(移动.网页.桌面.嵌入式). 现编一个跨平台小段子: 微软Xarmarin:喵喵喵? ...