常用类-CSV---OLEDB
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的更多相关文章
- Foundation框架下的常用类:NSNumber、NSDate、NSCalendar、NSDateFormatter、NSNull、NSKeyedArchiver
========================== Foundation框架下的常用类 ========================== 一.[NSNumber] [注]像int.float.c ...
- JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式
相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...
- Java集合常用类特点整理
集合的结构如下图所示: 集合的两个顶级接口分别为:Collection和Map Collection下有两个比较常用的接口分别是List(列表)和Set(集),其中List可以存储重复元素,元素是有序 ...
- Java集合框架(常用类) JCF
Java集合框架(常用类) JCF 为了实现某一目的或功能而预先设计好一系列封装好的具有继承关系或实现关系类的接口: 集合的由来: 特点:元素类型可以不同,集合长度可变,空间不固定: 管理集合类和接口 ...
- java-API中的常用类,新特性之-泛型,高级For循环,可变参数
API中的常用类 System类System类包含一些有用的类字段和方法.它不能被实例化.属性和方法都是静态的. out,标准输出,默认打印在控制台上.通过和PrintStream打印流中的方法组合构 ...
- Java基础复习笔记系列 五 常用类
Java基础复习笔记系列之 常用类 1.String类介绍. 首先看类所属的包:java.lang.String类. 再看它的构造方法: 2. String s1 = “hello”: String ...
- iOS 杂笔-24(常用类到NSObject的继承列表)
iOS 杂笔-24(常用类到NSObject的继承列表) NSString NSObject->NSString NSArray NSObject->NSArray ↑OC基本类都直接继承 ...
- java的eclipse操作和常用类Object的使用
1.eclipse的快捷键: (1)alt + / 内容辅助. 如:main+alt + / 会出现完整的main方法. syso+alt+ / 会输出. 如编写某个方法时,只需写入方法名 + a ...
- java总结第四次//常用类
六.常用类 主要内容:Object类.String类.Date类.封装类 (一)Object类 1.Object类是所有Java类的根父类 2.如果在类的声明中未使用extends关键字指明其父类,则 ...
- JAVA基础知识之IO——Java IO体系及常用类
Java IO体系 个人觉得可以用"字节流操作类和字符流操作类组成了Java IO体系"来高度概括Java IO体系. 借用几张网络图片来说明(图片来自 http://blog.c ...
随机推荐
- sql为什么用0,1表示男女?在sql语句里转好还是在页面转好?
转化语句:SELECT CASE `user_gender` WHEN '1' THEN '男' WHEN '0' THEN '未知'ELSE '女' END AS gender FROM `info ...
- DHCP服务相关实验
一.DHCP 相关介绍 1.dhcp服务相关 软件名: dhcp #DHCP服务软件包 dhcp-common #DHCP命令软件包(默认已安装) 服务名: dhcpd #DHCP服务名 dhcrel ...
- Ubuntu服务器登录与使用
1. 登录 从本地登录远程服务器 1.1 默认端口 # format: ssh user_name@ip_address cv@cv: ~$ ssh cv@192.168.1.1 1.2 登录到指定端 ...
- 比较typeof与instanceof
相同点: JavaScript中typeof和instanceof常用来判断一个变量是否为空,或者是什么类型的. 不同点: typeof的定义和用法: 返回值是一个字符串,用来说明变量的数据类型. 细 ...
- Vsftpd运行的两种模式-xinetd运行模式和 standalone模式
vsftpd运行的两种模式-xinetd运行模式和 standalone模式 vsftpd提供了standalone和inetd(inetd或xinetd)两种运行模式. standalone一次性启 ...
- C# 派生和继承(派生类与基类)
using System; using System.Collections.Generic; using System.Text; namespace 继承 { class Program { st ...
- C#中使用Path、Directory、Split、Substring实现对文件路径和文件名的常用操作实例
场景 现在有一个文件路径 E:\\BTSData\\2019-11\\admin_20180918_1_1_2 需要获取最后的文件名admin_20180918_1_1_2 需要获取文件的上层目录20 ...
- kotlin之变量的可空与非空
版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/218 kotlin之变量的可空与非空 上面一篇文章,介绍了 ...
- JMeter多脚本间的启动延时
JMeter做压测时,当需要多个jmx脚本依次执行时,需要用到“启动延时”,即间隔可设置的时间后启动运行下一个jmx脚本. 实现“启动延时”的方法有2个. 方法一.利用JMeter线程组中的" ...
- VS2019 开发Django(三)------连接MySQL
导航:VS2019开发Django系列 下班回到家,洗漱完毕,夜已深.关于Django这个系列的博文,我心中的想法就是承接之前的微信小程序的内容,做一个服务端的管理中心,上新菜单,调整价格啊!之类的, ...