文档库 最新最全的文档下载
当前位置:文档库 › Excel导入导出(DataTable)

Excel导入导出(DataTable)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.OleDb;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WinExcel
{
///


/// winForm程序导入导出EXCEL
///

///
/// 使用方法:
/// 读取EXCEL数据:ImportExcel();
/// 导出EXCEL:SaveAsExcel(system.data.datatable);
///

public class ReadWriterExcel
{

/// 用oledb方式读取excel到datatable
/// 文件存放路径
private static System.Data.DataTable GetData(string strPath)
{
System.Data.DataTable dt = new System.Data.DataTable();
try
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strPath + ";" + "Extended Properties=Excel 8.0;";
string strSheetName = "";
using (OleDbConnection con = new OleDbConnection(strCon))
{
con.Open();
System.Data.DataTable dtTemp = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
strSheetName = dtTemp.Rows[0][2].ToString().Trim();
}
String strCmd = "select * from [" + strSheetName + "]";
OleDbDataAdapter cmd = new OleDbDataAdapter(strCmd, strCon);
cmd.Fill(dt);
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
return dt;
}


/// winform程序,点击程序上的按钮,找到Excel文件,打开后把这个Excel里的数据导入到oracle数据库里
/// 文件路径
public static DataSet ImportExcel(string file)
{
FileInfo fileInfo = new FileInfo(file);
if (!fileInfo.Exists)
return null;

string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet dsExcel = new DataSet();
try
{
objConn.Open();
string strSql = "select * from [Sheet1$]";
OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
odbcExcelDataAdapter.Fill(dsExcel);
return dsExcel;
}
catch (Exception ex)
{
throw ex;
}
}


/// 导出到Excel
/// 数据源
public static void SaveAsExcel(System.Data.DataTable dtExcel)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();

saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != 0)
{
//导出到execl
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
excel.Application.Workbooks.Add(true);
excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
if (excel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
https://www.wendangku.net/doc/2b5294380.html, = "test";

int m = 0, n = 0;
//生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去
for (int i = 0; i < dtExcel.Columns.Count; i++)
{
excel.Cells[1, i + 1] = dtExcel.Columns[i].Caption.ToString();
}

//填充数据
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
//j也是从1开始 原因如上 每个人需求不一样
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
if (dtExcel.Rows[i][j].ToString().GetType() == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dtExcel.Rows[i][j].ToString().Trim();
}
else
{
excel.Cells[i + 2, j + 1] = dtExcel.Rows[i][j].ToString().Trim();
}
}
}

sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
book.Close(false, miss, miss);
books.Close();
excel

.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

GC.Collect();
MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, https://www.wendangku.net/doc/2b5294380.html,rmation);
//toolStripProgressBar1.Value = 0;
System.Diagnostics.Process.Start(strName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误提示");
}
finally
{
//excel.Quit();
KillSpecialExcel(excel);

}
}
}


//获得当前你选择的Excel Sheet的所有名字
private string[] GetExcelSheetNames(string filePath)
{
Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
int count = wb.Worksheets.Count;
string[] names = new string[count];
for (int i = 1; i <= count; i++)
{
names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name;
}
return names;
}


private void ReleaseExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
{
m_objExcel.Quit();

//System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objExcel);
//System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBooks);
//System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBook);
//System.Runtime.InteropServices.Marshal.ReleaseComObject((object)sheet);

//sheet = null;
//m_objBook = null;
//m_objBooks = null;
m_objExcel = null;

GC.Collect(0);
}

#region KillAllExcel 停止EXCEL进程

private bool KillAllExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
{
try
{
if (m_objExcel != null) // isRunning是判断xlApp是怎么启动的flag.
{
m_objExcel.Quit();
System.Runtime.InteropService

s.Marshal.ReleaseComObject(m_objExcel);
//释放COM组件,其实就是将其引用计数减1
//System.Diagnostics.Process theProc;
foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
{
//先关闭图形窗口。如果关闭失败...有的时候在状态里看不到图形窗口的excel了,
//但是在进程里仍然有EXCEL.EXE的进程存在,那么就需要杀掉它:p
if (theProc.CloseMainWindow() == false)
{
theProc.Kill();
}
}
m_objExcel = null;
return true;
}
}
catch
{
return false;
}
return true;
}

#endregion

#region Kill Special Excel Process

[DllImport("User32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

//推荐这个方法,找了很久,不容易啊
private static void KillSpecialExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
{
try
{
if (m_objExcel != null)
{
int lpdwProcessId;
GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
}
catch (Exception ex)
{
Console.WriteLine("Delete Excel Process Error:" + ex.Message);
}
}

#endregion

///


/// 导入EXCEL
///

/// System.Data.DataTable
public static System.Data.DataTable ImportExcel()
{
System.Data.DataTable dt;
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
dt = GetData(openfile.FileName);//获得Excel
}
catch (Exception ex)
{
throw ex;
}
}
else
{
dt = null;
}
return dt;
}
}
}

相关文档
相关文档 最新文档