using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections;
using System.IO; /*
当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。 当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。 当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。
*/
/* 列类型 经典 ADO ADO.Net (OleDb)
数字 5-adDouble 5-OleDbType.Double
货币 6-adCurrency 6-OleDbType.Currency
日期/时间 7-adDate 7-OleDbType.Date
布尔值 11-adBoolean 11-OleDbType.Boolean
文本 < 255 202-adVarWChar 130-OleDbType.WChar
备注 203-adLongVarWChar 130-OleDbType.WChar
*/ namespace ExcelGenerator
{
/// <summary>
/// http://support.microsoft.com/zh-cn/kb/318452
/// http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled
/// 20150325
/// 涂聚文
/// </summary>
public partial class ExcelFileForm : Form
{
//"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\\test.xls;Extended Properties=Excel 8.0";
//Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsm;Extended Properties = "Excel 12.0 Macro;HDR=YES";
//Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myBinaryExcel2007file.xlsb;Extended Properties="Excel 12.0;HDR=YES";
//Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties = "Excel 8.0;HDR=YES";
//Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls; Extended Properties = "Excel 8.0;HDR=Yes;IMEX=1";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\\test.xls;Extended Properties=Excel 8.0;HDR=Yes;IMEX=1;";
private OleDbConnection cn; private DataTable dtTables;
private CurrencyManager cm;
private DataTable dtColumns;
private DataView dvColumns; string fileurl = string.Empty;
/// <summary>
/// GetOleDbSchemaTable(OleDbSchemaGuid.Columns,new Object[]{null,null, strTable, null});
/// </summary>
/// <returns></returns>
private DataTable setTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id",typeof(int));
dt.Columns.Add("name", typeof(string));
dt.Rows.Add(1, "tables");//工作表
dt.Rows.Add(2, "Columns");
//dt.Rows.Add(3, "");
//dt.Rows.Add(4, "");
//dt.Rows.Add(5, "");
//dt.Rows.Add(6, ""); return dt;
} /// <summary>
/// /
/// </summary>
public ExcelFileForm()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ExcelFileForm_Load(object sender, EventArgs e)
{
this.comboBox1.DataSource = setTable();
this.comboBox1.DisplayMember = "name";
this.comboBox1.ValueMember = "id";
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Excel 2000-2003 files(*.xls)|*.xls|Excel 2007 files (*.xlsx)|*.xlsx";//|(*.xlsx)|*.xlsx Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.* txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!openFileDialog1.FileName.Equals(String.Empty))
{ //connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=Excel 8.0;";
fileurl = openFileDialog1.FileName; string extension = Path.GetExtension(fileurl); //GetFileNameWithoutExtension
this.textBox1.Text = openFileDialog1.FileName;
if (extension == ".xls") //extension==".xls";
{
connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileurl + ";" +
@"Extended Properties=" + "\"Excel 8.0;HDR=YES;\"";
}
else if (extension==".xlsx")//extension==".xlsx";
{
connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + fileurl + ";" +
@"Extended Properties=" + "\"Excel 12.0;HDR=YES;\"";
}
}
}
}
/// <summary>
/// TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE,TABLE_GUID,DESCRIPTION,TABLE_PROPID,DATE_CREATED,DATE_MODIFIED
/// TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,COLUMN_GUID,COLUMN_PROPID,ORDINAL_POSITION,COLUMN_HASDEFAULT,COLUMN_DEFAULT,COLUMN_FLAGS,IS_NULLABLE,DATA_TYPE,TYPE_GUID,CHARACTER_MAXIMUM_LENGTH,CHARACTER_OCTET_LENGTH,NUMERIC_PRECISION,NUMERIC_SCALE,DATETIME_PRECISION,CHARACTER_SET_CATALOG,CHARACTER_SET_SCHEMA,CHARACTER_SET_NAME,COLLATION_CATALOG,COLLATION_SCHEMA,COLLATION_NAME,DOMAIN_CATALOG,DOMAIN_SCHEMA,DOMAIN_NAME,DESCRIPTION
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection(connectionString);
ExcelConnection.Open();
//dtTables = ExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//dtTables = ExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, null, "Sheet1$" });
//dtTables = ExcelConnection.GetSchema("tables");
//this.dataGridView1.DataSource = dtTables;
//ExcelConnection.Close();
//this.textBox2.Text = GetColumnNames(dtTables); GetTablesList();
this.dataGridView2.DataSource= ReadExcelFile().Tables[0]; }
/// <summary>
///
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static string GetColumnNames(System.Data.DataTable table)
{
if (table != null)
{
List<string> lstColumn = new List<string>(); foreach (System.Data.DataColumn col in table.Columns)
{
lstColumn.Add(col.ColumnName);
} return String.Join(",", lstColumn.ToArray());
} return string.Empty;
//foreach (DataRow row in table.Rows)
//{
// foreach (DataColumn column in table.Columns)
// {
// ColumnName = column.ColumnName;
// ColumnData = row[column].ToString();
// }
//}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{ }
/// <summary>
///
/// </summary>
private void GetTablesList()
{
try
{
cn = new OleDbConnection(connectionString);
cn.Open();
dtTables = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
this.dataGridView3.DataSource = dtTables;
//dataGridView1.ReadOnly = true;
cn.Close();
}
catch (System.Data.OleDb.OleDbException myException)
{
for (int i = 0; i < myException.Errors.Count; i++)
{
MessageBox.Show("Index #" + i + "\n" +
"Message: " + myException.Errors[i].Message + "\n" +
"Native: " +
myException.Errors[i].NativeError.ToString() + "\n" +
"Source: " + myException.Errors[i].Source + "\n" +
"SQL: " + myException.Errors[i].SQLState + "\n");
}
} GetColumnsList();
}
/// <summary>
///
/// </summary>
private void GetColumnsList()
{
try
{
if (cm == null)
cm = (CurrencyManager)this.BindingContext[dtTables]; cm.PositionChanged += new EventHandler(cm_PositionChanged); int r = cm.Position; String strTable = dtTables.Rows[r]["TABLE_NAME"].ToString();
cn = new OleDbConnection(connectionString);
cn.Open();
dtColumns = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, strTable, null });//字段名
dvColumns = new DataView(dtColumns);
dvColumns.Sort = "ORDINAL_POSITION";
dataGridView1.DataSource = dvColumns;
//dataGridView1.ReadOnly = true;
cn.Close(); this.textBox2.Text = GetColumnNames(dtColumns);
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cm_PositionChanged(object sender, System.EventArgs e)
{
GetColumnsList();
} private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{ }
/// <summary>
///
/// </summary>
/// <param name="dt2format"></param>
private void FormatTablesGrid(DataTable dt2format)
{
DataGridTableStyle gs = new DataGridTableStyle();
gs.MappingName = dt2format.TableName; DataGridColumnStyle cs = new DataGridTextBoxColumn(); cs.MappingName = "TABLE_NAME";
cs.HeaderText = "Table Name";
cs.Width = 75; gs.GridColumnStyles.Add(cs); cs = new DataGridTextBoxColumn();
cs.MappingName = "TABLE_TYPE";
cs.HeaderText = "Table Type";
cs.Width = 75; gs.GridColumnStyles.Add(cs); CurrencyManager cm = (CurrencyManager)this.BindingContext[dt2format]; PropertyDescriptor pd = cm.GetItemProperties()["DATE_CREATED"]; cs = new DataGridTextBoxColumn(pd, "d");
cs.MappingName = "DATE_CREATED";
cs.HeaderText = "Date Created";
cs.Width = 75; gs.GridColumnStyles.Add(cs); cm = (CurrencyManager)this.BindingContext[dt2format];
pd = cm.GetItemProperties()["DATE_MODIFIED"]; cs = new DataGridTextBoxColumn(pd, "d");
cs.MappingName = "DATE_MODIFIED";
cs.HeaderText = "Date Modified";
cs.Width = 75; gs.GridColumnStyles.Add(cs); //dataGridView1.TabIndex.Add(gs);
button2.Enabled = false; }
/// <summary>
/// http://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
/// </summary>
/// <returns></returns>
private string GetConnectionString()
{
Dictionary<string, string> props = new Dictionary<string, string>(); // XLSX - Excel 2007, 2010, 2012, 2013
//props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
//props["Extended Properties"] = "Excel 12.0 XML;"; //
//props["Data Source"] = fileurl; // XLS - Excel 2003 and Older
//props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
//props["Extended Properties"] = "Excel 8.0;";//HDR=Yes;IMEX=1
//props["Data Source"] = fileurl;
//fileurl = this.textBox1.Text.Trim();
string extension = Path.GetExtension(fileurl);
if (extension == ".xls") //extension==".xls";
{
connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileurl + ";" +
@"Extended Properties=" + "\"Excel 8.0;HDR=YES;\""; // XLS - Excel 2003 and Older
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Extended Properties"] = "Excel 8.0";//HDR=Yes;IMEX=1
props["Data Source"] = fileurl;
}
else if (extension == ".xlsx")//extension==".xlsx";
{
connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + fileurl + ";" +
@"Extended Properties=" + "\"Excel 12.0;HDR=YES;\"";
// XLSX - Excel 2007, 2010, 2012, 2013
props["Provider"] = "Microsoft.ACE.OLEDB.12.0";
props["Data Source"] = fileurl;
props["Extended Properties"] = "Excel 12.0 XML"; //Excel 12.0 XML } StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
} return sb.ToString();
}
/// <summary>
/// 创建工作表table1
/// </summary>
private void WriteExcelFile()
{
string connectionString = GetConnectionString(); using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn; cmd.CommandText = "CREATE TABLE [table1] (id INT, name VARCHAR, datecol DATE );";//创建工作表table1 及表头
cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO [table1](id,name,datecol) VALUES(1,'AAAA','2014-01-01');";
cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO [table1](id,name,datecol) VALUES(2, 'BBBB','2014-01-03');";
cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO [table1](id,name,datecol) VALUES(3, 'CCCC','2014-01-03');";
cmd.ExecuteNonQuery(); cmd.CommandText = "UPDATE [table1] SET name = 'DDDD' WHERE id = 3;";
cmd.ExecuteNonQuery(); conn.Close();
}
}
/// <summary>
/// 读工作表
/// </summary>
/// <returns></returns>
private DataSet ReadExcelFile()
{
DataSet ds = new DataSet(); string connectionString = GetConnectionString(); try
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn; // Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); // Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString(); if (!sheetName.EndsWith("$"))
continue; // Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]"; DataTable dt = new DataTable();
dt.TableName = sheetName; OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt); ds.Tables.Add(dt);
} cmd = null;
conn.Close();
} }
catch (Exception ex)
{
ex.Message.ToString();
}
return ds;
}
/// <summary>
/// 添加一个新工作表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
WriteExcelFile();
}
/// <summary>
/// 查询值
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
//create a string for the query string ExcelQuery; //Sheet1 is the sheet name
//create the query:
//read column with heading A from the Excel file
ArrayList ad = new ArrayList();
ExcelQuery = "SELECT * FROM [Sheet1$] WHERE 序号=5"; // from Sheet1";
DataSet ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
//1.
OleDbCommand cmd = new OleDbCommand(ExcelQuery, conn);
conn.Open();
OleDbDataReader myReader = cmd.ExecuteReader();
if (myReader.Read())
{
ad.Add(myReader[0].ToString()+","+myReader[1].ToString()+","+myReader[2].ToString()+","+myReader[3].ToString()+","+myReader[4].ToString());
}
this.textBox2.Text= String.Join(",", ad.ToArray()); //2.
//OleDbDataAdapter command = new OleDbDataAdapter(ExcelQuery, connectionString);
//command.Fill(ds, "ds");
//dataGridView1.DataSource = ds.Tables[0];
} } } }

  数据类型:

Short System.Int16 2
Long System.Int32 3
Single System.Single 4
Double System.Double 5
Currency System.Decimal 6
DateTime System.DateTime 7
Bit System.Boolean 11
Byte System.Byte 17
GUID System.Guid 72
BigBinary System.Byte[] 204
LongBinary System.Byte[] 205
VarBinary System.Byte[] 204
LongText System.String 203
VarChar System.String 202
Decimal System.Decimal 131

/*
MetaDataCollections
DataSourceInformation
DataTypes
Restrictions
ReservedWords
Columns
Indexes
Procedures
Tables
Views
*/

Excel Metadata的更多相关文章

  1. SQLite metadata

    http://www.devart.com/dotconnect/sqlite/docs/MetaData.html https://github.com/sqlitebrowser/sqlitebr ...

  2. Excel解析easyexcel工具类

    Excel解析easyexcel工具类 easyexcel解决POI解析Excel出现OOM <!-- https://mvnrepository.com/artifact/com.alibab ...

  3. java五行代码导出Excel

    目录 先看代码 再看效果 EasyExcel 附: Java按模板导出Excel---基于Aspose实现 Java无模板导出Excel,Apache-POI插件实现 已经写过两种Excel导出插件了 ...

  4. Excel解析工具easyexcel全面探索

    1. Excel解析工具easyexcel全面探索 1.1. 简介 之前我们想到Excel解析一般是使用POI,但POI存在一个严重的问题,就是非常消耗内存.所以阿里人员对它进行了重写从而诞生了eas ...

  5. SpringBoot整合easyexcel实现Excel的导入与导出

    导出 在一般不管大的或者小的系统中,各家的产品都一样,闲的无聊的时候都喜欢让我们这些程序员导出一些数据出来供他观赏,非说这是必须需求,非做不可,那么我们就只能苦逼的哼哧哼哧的写bug喽. 之前使用PO ...

  6. 使用 EasyExcel 读取Excel(两种方式)

    引入 jar 包 <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel&l ...

  7. JAVA使用easyexcel操作Excel

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.                                               本 ...

  8. EasyExcel实现导入excel

    https://blog.csdn.net/rexueqingchun/article/details/91870372 1.pom.xml配置依赖包 <!-- xls格式excel依赖包 -- ...

  9. SpringBoot基于easyexcel导出和写入Excel

      easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件. 一.加入我们需要的ea ...

随机推荐

  1. CentOS6.5下samba服务

    为减少错误已提前关掉了SELinux,防火墙. 安装rpm包: samba-3.6.9-164.el6.x86_64.rpm 启动检测:samba服务可以正常启动!(证明RPM安装正常) 配置文件位置 ...

  2. Spring AOP 概述

    1. AOP的概念 AOP 是Aspect-Oriented Programming(面向方面编程或者面向切面)的简称,维基百科对其解释如下: Aspect是一种新的模块化机制,用来描述分散在对象.类 ...

  3. CF1007D. Ants(树链剖分+线段树+2-SAT及前缀优化建图)

    题目链接 https://codeforces.com/problemset/problem/1007/D 题解 其实这道题本身还是挺简单的,这里只是记录一下 2-SAT 的前缀优化建图的相关内容. ...

  4. (四)Audio子系统之AudioRecord.read

      在上一篇文章<(三)Audio子系统之AudioRecord.startRecording>中已经介绍了AudioRecord如何开始录制音频,接下来,继续分析AudioRecord方 ...

  5. Python对象引用和del删除引用

    1.首先介绍下python的对象引用 1)Python中不存在传值调用,一切传递的都是对象引用,也可以认为是传址调用.即Python不允许程序员选择采用传值或传引用.Python参数传递采用的是“传对 ...

  6. 【文档】四、Mysql Binlog事件含义详解

    下面对binlog中事件做个简单说明: UNKNOWN_EVENT 这个事件类型应该永远不会出现.它从不会写入binlog中.如果binlog中的事件没法被识别成其他已知事件,他被当做UNKNOWN_ ...

  7. redis 常用的server的命令

  8. zend studio 连PHP自带系统函数 常量都不提示

    如果是新建项目,所有PHP文件里面函数都是可以自带提示的. 但是,打开已经建立好的项目时候,貌似无法识别是PHP项目或者其他什么. 此时,在项目上点击: configure->add php s ...

  9. EasyMock set方法报错: java.lang.AssertionError

    有返回值的方法没问题, 直接andReturn就行了. EasyMock.expect(info.getWebTitle()).andReturn(StringUtils.EMPTY).anyTime ...

  10. java中为什么重写equals时必须重写hashCode方法?

    在上一篇博文Java中equals和==的区别中介绍了Object类的equals方法,并且也介绍了我们可在重写equals方法,本章我们来说一下为什么重写equals方法的时候也要重写hashCod ...