利用Oledb操作XLS文件
简介:
解决方案:
Form1.designer.cs:
namespace XlsViaOledb
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(12, 34);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ShowCellToolTips = false;
this.dataGridView1.Size = new System.Drawing.Size(504, 233);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView1_DataError);
this.dataGridView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGridView1_MouseDown);
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(113, 9);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(130, 20);
this.comboBox1.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(95, 12);
this.label1.TabIndex = 2;
this.label1.Text = "Select a sheet:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(290, 9);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 21);
this.button1.TabIndex = 3;
this.button1.Text = "Show";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// toolTip1
//
this.toolTip1.IsBalloon = true;
this.toolTip1.UseAnimation = false;
this.toolTip1.UseFading = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(528, 278);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ToolTip toolTip1;
}
}
Form.cs
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;
namespace XlsViaOledb
{
public partial class Form1 : Form
{
OleDbConnection conn;
OleDbDataAdapter adapter;
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// connect to xls file
// NOTE: it will be created if not exists
conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;" +
"Data Source=" + Application.StartupPath + "\\test.xls;" +
"Extended Properties=Excel 8.0");
conn.Open();
// create a sheet "Sheet1" if not exists
// NOTE: no "id" field needed
// WARNING: spaces in sheet's name are supported if names are in [] (automatically replace with _)
// spaces in column names NOT supported with OleDbCommandBuilder!
try
{
string cmdText = "CREATE TABLE [Sheet 1] (text_col MEMO, int_col INT)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
cmd.ExecuteNonQuery();
}
}
catch { }
// get sheets list into combobox
dt = conn.GetSchema("Tables");
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
if (dt.Rows[i].ItemArray[dt.Columns.IndexOf("TABLE_TYPE")].ToString() == "TABLE" &&
!dt.Rows[i].ItemArray[dt.Columns.IndexOf("TABLE_NAME")].ToString().Contains("$"))
{
comboBox1.Items.Add(dt.Rows[i].ItemArray[dt.Columns.IndexOf("TABLE_NAME")]);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
adapter = new OleDbDataAdapter("SELECT * FROM " + comboBox1.SelectedItem.ToString(), conn);
new OleDbCommandBuilder(adapter);
dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (adapter == null) return;
adapter.Update(dt);
}
// show tooltip (not intrusive MessageBox) when user trying to input letters into INT column cell
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (dt.Columns[e.ColumnIndex].DataType == typeof(Double))
{
Rectangle rectColumn;
rectColumn = dataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, false);
Rectangle rectRow;
rectRow = dataGridView1.GetRowDisplayRectangle(e.RowIndex, false);
toolTip1.ToolTipTitle = "This field is for integers and decimals only.";
toolTip1.Show(" ",
dataGridView1,
rectColumn.Left, rectRow.Top + rectRow.Height);
}
}
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
toolTip1.Hide(dataGridView1);
}
}
}