C# SQL与EXCLE数据互导

EXCEL表里的数据导入SQL中,简化代码

View Code
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.SqlClient;
using System.Data.OleDb;
using System.Collections;
using System.IO;

namespace SqlExcel
{
publicpartialclass Form2 : Form
{
public Form2()
{
InitializeComponent();
}
SqlHelper sqlhelper
=new SqlHelper();

///
/// 选择excle路径
///

///
///
privatevoid button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog dialog =new OpenFileDialog())
{
dialog.Multiselect
=true;
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
textBox1.Text
= dialog.FileName;
}
catch { }
}
}

}
///
/// 先把excle读到Dataset里
///

///文件路径名
///
public DataSet ExecleDs(string filenameurl)
{

string strConn ="Provider=Microsoft.Jet.OleDb.4.0;"+"data source="+ filenameurl +";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn
=new OleDbConnection(strConn);
OleDbCommand cmd
=new OleDbCommand("select * from [Sheet1$]",conn);
OleDbDataAdapter odda
=new OleDbDataAdapter(cmd);
DataSet ds
=new DataSet();
odda.Fill(ds);
return ds;
}

///
/// 把Dataset里的数据一行一行的插入到数据表里
///

///
///
privatevoid button2_Click(object sender, EventArgs e)
{
int ii =0;
DataSet ds
= ExecleDs(textBox1.Text);
System.Data.DataTable dt
= ds.Tables[0];

try
{
string strInsertComm;
for (int i =0; i < dt.Rows.Count; i++)
{
strInsertComm
="";
strInsertComm
="Insert INTO T_Student(F_Num,F_Name,F_Sex,F_Dept)";
strInsertComm
+=" values(";
for (int j =0; j < dt.Columns.Count; j++)
{
if (j >0)
{
strInsertComm
+=",'"+ dt.Rows[i][j].ToString().Trim() +"'";
}
else
{
strInsertComm
+="'"+ dt.Rows[i][j].ToString().Trim() +"'";
}
}
strInsertComm
+=")";
ii
= sqlhelper.getcomnum(strInsertComm);//执行SQL语句
}
if (ii >0)
{
MessageBox.Show(
"导入成功!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

EXCEL表里的数据导入SQL中,完整代码(代码是从EXCEL2007导入到数据库的,如果想从2003中导入,则将Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1' 改为Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1')

View Code
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.SqlClient;
using System.Data.OleDb;
using System.Collections;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;




namespace SqlExcel
{
publicpartialclass Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlHelper sqlhelper
=new SqlHelper();
privatevoid Form1_Load(object sender, EventArgs e)
{

}

#region Excel导入SQL数据库
///
/// 选择要向SQL数据库中导入数据的Excel文件
///

privatevoid btnChoose_Click(object sender, EventArgs e)
{
using (OpenFileDialog dialog =new OpenFileDialog())
{
dialog.Multiselect
=true;
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
txtPath.Text
= dialog.FileName;
}
catch { }
}
}
}

///
/// 获取Excel数据表列表
///

///
publicstatic ArrayList GetExcelTables(string FilePath)
{
//将Excel架构存入数据里
System.Data.DataTable dt =new System.Data.DataTable();
ArrayList TablesList
=new ArrayList();

if (File.Exists(FilePath))
{
using (OleDbConnection conn =new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=\"Excel 8.0; HDR=YES; IMEX=1\";Data Source="+ FilePath))
{
try
{
conn.Open();
dt
= conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, newobject[] { null, null, null, "TABLE" });
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}

//获取数据表个数
int tablecount = dt.Rows.Count;
for (int i =0; i < tablecount; i = i +2)
{
string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');
if (TablesList.IndexOf(tablename) <0)
{
TablesList.Add(tablename);
}

}
}
}
return TablesList;
}

///
/// 导入Excel数据表至DataTable(第一行作为表头)
///

///
publicstatic System.Data.DataSet FillDataSet(string FilePath)
{
if (!File.Exists(FilePath))
{
thrownew Exception("Excel文件不存在!");
}

ArrayList TableList
=new ArrayList();
TableList
= GetExcelTables(FilePath);
if (TableList.Count <=0)
{
returnnull;
}

System.Data.DataTable table;
System.Data.DataSet ds
=new DataSet();
OleDbConnection dbcon
=new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ FilePath +";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'");
try
{
if (dbcon.State == ConnectionState.Closed)
{
dbcon.Open();
}
for (int i =0; i < TableList.Count; i++)
{
string dtname = TableList[i].ToString();
try
{
OleDbCommand cmd
=new OleDbCommand("select * from [Sheet1$]", dbcon);
OleDbDataAdapter adapter
=new OleDbDataAdapter(cmd);
table
=new System.Data.DataTable();
adapter.Fill(table);
ds.Tables.Add(table);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
finally
{
if (dbcon.State == ConnectionState.Open)
{
dbcon.Close();
}
}
return ds;
}

///
/// Excel导入数据库
///

///
publicstatic DataSet ImportFromExcel(string FilePath)
{
return FillDataSet(FilePath);
}

///
/// 将Excel中的数据导入到SQL数据库中
///

privatevoid btnExcelToSql_Click(object sender, EventArgs e)
{
int ii =0;
DataSet ds
= ImportFromExcel(txtPath.Text);
System.Data.DataTable dt
= ds.Tables[0];

try
{
string strInsertComm;
for (int i =0; i < dt.Rows.Count; i++)
{
strInsertComm
="";
strInsertComm
="Insert INTO T_Student(F_Num,F_Name,F_Sex,F_Dept)";
strInsertComm
+=" values(";
for (int j =0; j < dt.Columns.Count; j++)
{
if (j >0)
{
strInsertComm
+=",'"+ dt.Rows[i][j].ToString().Trim() +"'";
}
else
{
strInsertComm
+="'"+ dt.Rows[i][j].ToString().Trim() +"'";
}
}
strInsertComm
+=")";
ii
= sqlhelper.getcomnum(strInsertComm);
}
if (ii >0)
{
MessageBox.Show(
"导入成功!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion

下面为SQL2005里的数据导出到EXCEL中,先添加excel引用,再加上using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;这两个命名空间,代码如下:

View Code
#region sql数据库导出Excel
publicvoid Export(string tableName)
{

DataSet ds1
= sqlhelper.getds("select F_Num as '学 号',F_Name as '姓 名',F_Sex as '性 别',F_Dept as '所有系院' from "+ tableName, tableName);
if (ds1 ==null)
{
MessageBox.Show(
"系统内部错误!请联系系统开发者!", "出错了:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
string saveFileName ="";
SaveFileDialog saveDialog
=new SaveFileDialog();
saveDialog.DefaultExt
="xls";
saveDialog.Filter
="Excel文件|*.xls";
saveDialog.FileName
="";
saveDialog.ShowDialog();
saveFileName
= saveDialog.FileName;
if (saveFileName.IndexOf(":") <0)
{
MessageBox.Show(
"您取消了导出操作!", "提示信息:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}

Microsoft.Office.Interop.Excel.Application xlApp
=new Microsoft.Office.Interop.Excel.Application();
object miss = System.Reflection.Missing.Value;

if (xlApp ==null)
{
MessageBox.Show(
"无法创建Excel对象,可能您的机子未安装Excel!", "出错了:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}


Microsoft.Office.Interop.Excel.Workbooks workbooks
= xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook
= workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet
= (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Microsoft.Office.Interop.Excel.Range range;


//总行数和总列数
long totalRowCount = ds1.Tables[0].Rows.Count;
long totalColCount = ds1.Tables[0].Columns.Count;

//写入第一行表头
for (int i =0; i < totalColCount; i++)
{
worksheet.Cells[
1, i +1] = ds1.Tables[0].Columns[i].ColumnName;
range
= (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i +1];
range.Interior.ColorIndex
=15;
range.Font.Size
=15;//设定标题的大小
range.Columns.AutoFit();//自动调整报表表格宽度为最适合宽度
range.Font.Bold =true;
}


//写入数值
for (int r =0; r < totalRowCount; r++)
{
for (int i =0; i < totalColCount; i++)
{
worksheet.Cells[r
+2, i +1] = ds1.Tables[0].Rows[r][i].ToString();
range
= (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r +2, 1];//设置第一列为自动调整宽度
range.Columns.AutoFit();
}

}

range
= worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[ds1.Tables[0].Rows.Count +1, ds1.Tables[0].Columns.Count]);

if (totalRowCount >0)
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex
= Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle
= Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight
= Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;

}

if (totalColCount >1)
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].ColorIndex
= Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle
= Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight
= Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;

}

if (range !=null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range
=null;
}

if (worksheet !=null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet
=null;
}
if (saveFileName !="")
{
try
{
workbook.Saved
=true;
System.Reflection.Missing missing
= System.Reflection.Missing.Value;
workbook.SaveAs(saveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, miss, miss, miss, miss,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss);
MessageBox.Show(
"导出成功!", "提示信息:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
catch (Exception ex)
{
MessageBox.Show(
"导出文件错误!请重试!", "出错了:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

if (workbook !=null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook
=null;

}

if (workbooks !=null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
workbooks
=null;

}

xlApp.Application.Workbooks.Close();

xlApp.Quit();
GC.Collect();
}

privatevoid button1_Click(object sender, EventArgs e)
{
Export(
"T_Student");
}
#endregion

你可能感兴趣的:(C# SQL与EXCLE数据互导)