Excel Metadata
- 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的更多相关文章
- SQLite metadata
http://www.devart.com/dotconnect/sqlite/docs/MetaData.html https://github.com/sqlitebrowser/sqlitebr ...
- Excel解析easyexcel工具类
Excel解析easyexcel工具类 easyexcel解决POI解析Excel出现OOM <!-- https://mvnrepository.com/artifact/com.alibab ...
- java五行代码导出Excel
目录 先看代码 再看效果 EasyExcel 附: Java按模板导出Excel---基于Aspose实现 Java无模板导出Excel,Apache-POI插件实现 已经写过两种Excel导出插件了 ...
- Excel解析工具easyexcel全面探索
1. Excel解析工具easyexcel全面探索 1.1. 简介 之前我们想到Excel解析一般是使用POI,但POI存在一个严重的问题,就是非常消耗内存.所以阿里人员对它进行了重写从而诞生了eas ...
- SpringBoot整合easyexcel实现Excel的导入与导出
导出 在一般不管大的或者小的系统中,各家的产品都一样,闲的无聊的时候都喜欢让我们这些程序员导出一些数据出来供他观赏,非说这是必须需求,非做不可,那么我们就只能苦逼的哼哧哼哧的写bug喽. 之前使用PO ...
- 使用 EasyExcel 读取Excel(两种方式)
引入 jar 包 <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel&l ...
- JAVA使用easyexcel操作Excel
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明. 本 ...
- EasyExcel实现导入excel
https://blog.csdn.net/rexueqingchun/article/details/91870372 1.pom.xml配置依赖包 <!-- xls格式excel依赖包 -- ...
- SpringBoot基于easyexcel导出和写入Excel
easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件. 一.加入我们需要的ea ...
随机推荐
- springMVC传递一组对象的接受方式
受益此大神:https://blog.csdn.net/cgd_8523/article/details/80022331 同时借鉴代码!!!! 我只用了一种方法,就记下这一种 需求:前台存在动态添加 ...
- max,min无法使用的问题
遇到了包含algorithm头文件以后 min或max函数不能用的问题 改成__min和__max以后就可以了
- Java中关键字final用法
///首先声明,本文转载自博客园的海子,链接:http://www.cnblogs.com/dolphin0520/p/3736238.html 浅析Java中的final关键字 谈到final关键字 ...
- KMP算法再解 (看毛片算法真是人如其名,哦不,法如其名。)
KMP算法主要解决字符串匹配问题,其中失配数组next很关键: 看毛片算法真是人如其名,哦不,法如其名. 看了这篇博客,转载过来看一波: 原博客地址:https://blog.csdn.net/sta ...
- vue环境搭建简介
简单整理下vue的安装的新建项目 安装node.js和npm 参考其他教程 安装vue npm install vue 安装脚手架 vue-cli npm install --global vue-c ...
- 常见 CentOS 7 安装问题
问题一: 解决办法:网上安装文章推荐的的刻录工具多是 ultraiso,有时候可能会出现错误,这时候最简单的解决办法是换由RedHat推荐的刻录工具,fedora media writer,不过这个工 ...
- 微信 oauth 登录 ,回调两次,一个坑,记录一下。
在做微信某个功能的时候,大致需求是:静默授权,得到openId ,然后拿着openId调用接口,判断是否关注.如果是关注的,则发放礼券.每个我网站的会员只会发放一次礼券.如果第二次则会提示已领取过礼券 ...
- ActionBarCompat 教程-实现Action Bar
http://www.mobiletuts.me 自Action Bar设计概念在Android 3.0(API 11) 中被Google引入以后,Action Bar这种设计模式迅速被各APP厂商( ...
- (转)OpenStack构架知识梳理
http://www.cnblogs.com/kevingrace/p/8459034.html-------------------Openstack架构概念图-简单汇总 原文:http://www ...
- 关于c#中委托与事件的一些理解
文章目的:作者(初学者)在学习c#的过程中,对事件.委托及其中的“object sender,EventArgs e”一直感觉理解不透,因此在网上找了一些资料,学习并整理出了该篇笔记,希望能将自己的心 ...