文章目錄
其實讀取Excel表格中的資料和讀取資料庫中的資料是非常類似的,因為在某種程度上Excel表格可以看成是一張一張的資料表。其二者的主要區別在於所使用的資料引擎不一樣。在本文的程式中,通過下列代碼實現讀取Excel表格式資料,具體如下:
//建立一個資料連結
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = c:\\sample.xls;Extended Properties=Excel 8.0" ;
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
string strCom = " SELECT * FROM [Sheet1$] " ;
myConn.Open ( ) ;
file://開啟資料連結,得到一個資料集
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
file://建立一個 DataSet對象
myDataSet = new DataSet ( ) ;
file://得到自己的DataSet對象
myCommand.Fill ( myDataSet , "[Sheet1$]" ) ;
file://關閉此資料連結
myConn.Close ( ) ;
怎麼樣讀取Excel表格中的資料其實和讀取資料庫中的資料沒有什麼實質上的區別。
注釋:這裡讀取的是C盤根目錄下的"Sample.xls"檔案。
---------------------------------------------------------------------
Feedback#1樓 [樓主] 回複 引用 查看
2006-10-25 19:25 by 小y 將資料庫表匯出到Excel,並組建檔案(C#實現)
關鍵詞: C#, ASP.NET, Excel
需添加項目引用:
1. .NET->System.Data.OracleClient.dll
2. COM->Microsoft Excel 11.0 Object Library
代碼如下:
using System;
using System.IO;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Collections;
using Excel;
namespace ProtoType
{
///
/// 套用模板輸出Excel,產生xls檔案和html檔案
/// Author: Liu Wen
/// Date Created: 2006-8
///
public class ExportExcel
{
#region variable member
protected string templateFile = null;
protected string excelFile = null;
protected string htmlFile = null;
protected object missing = Missing.Value;
Excel.ApplicationClass app;
Excel.Workbook book;
Excel.Worksheet sheet;
Excel.Range range;
private DateTime beforeTime; //Excel啟動之前時間
private DateTime afterTime; //Excel啟動之後時間
#endregion
///
/// 建構函式,將一個已有Excel活頁簿作為模板,並指定輸出路徑
///
/// Excel模板檔案路徑
/// Excel輸出檔案路徑
/// Html輸出檔案路徑
public ExportExcel(string templateFile, string excelFile, string htmlFile)
{
if(templateFile == null)
throw new Exception("Excel模板檔案路徑不可為空!");
if(excelFile == null)
throw new Exception("Excel輸出檔案路徑不可為空!");
if(htmlFile == null)
throw new Exception("Html輸出檔案路徑不可為空!");
if(!File.Exists(templateFile))
throw new Exception("指定路徑的Excel模板檔案不存在!");
this.templateFile = templateFile;
this.excelFile = excelFile;
this.htmlFile = htmlFile;
//建立一個Application對象
beforeTime = DateTime.Now;
app = new ApplicationClass();
//app.Visible = true;
afterTime = DateTime.Now;
//開啟模板檔案,得到WorkBook對象
try
{
book = app.Workbooks.Open(templateFile,missing,missing,missing,missing,missing,
missing,missing,missing,missing,missing,missing,missing,missing,missing);
}
catch (Exception e)
{
throw e;
}
//得到WorkSheet對象
sheet = (Excel.Worksheet)book.Sheets.get_Item(1);
}
///
/// 將DataTable資料匯出到Excel(可動態插入行)
///
/// DataTable
/// 插入行的索引
/// 插入列的索引
public void DataTableToExcel(System.Data.DataTable dt, int rowIndex, int colIndex)
{
//range = sheet.get_Range("A7", missing);
//range.Value2 = "raogerrr";
//string str = range.Text.ToString();
int rowCount = dt.Rows.Count; //DataTable行數
int colCount = dt.Columns.Count; //DataTable列數
int iRow;
int iCol;
//將資料匯出到相應的儲存格
for (iRow = 0; iRow < rowCount; iRow++)
{
//插入新行
this.InsertRows(sheet, iRow+rowIndex);
//填充當前行
for (iCol = 0; iCol < colCount; iCol++)
{
sheet.Cells[iRow+rowIndex, iCol+colIndex] = dt.Rows[iRow][iCol].ToString();
}
}
this.DeleteRows(sheet, rowCount+rowIndex);
//Excel.QueryTables qts = sheet.QueryTables;
//Excel.QueryTable qt = qts.Add(,,);
//qt.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;
//qt.Refresh();
}
///
/// 將DataTable資料匯出到Excel(可動態插入行)
///
/// DataTable
/// 插入資料的起始儲存格
public void DataTableToExcel(System.Data.DataTable dt, string cellID)
{
int rowIndex = sheet.get_Range(cellID, missing).Row;
int colIndex = sheet.get_Range(cellID, missing).Column;
int rowCount = dt.Rows.Count; //DataTable行數
int colCount = dt.Columns.Count; //DataTable列數
int iRow;
int iCol;
//利用二維數組批量寫入
string[,] array = new string[rowCount,colCount];
for (iRow = 0; iRow < rowCount; iRow++)
{
for (iCol = 0; iCol < colCount; iCol++)
{
array[iRow,iCol] = dt.Rows[iRow][iCol].ToString();
}
}
for (iRow = 0; iRow < rowCount; iRow++)
{
this.InsertRows(sheet, iRow+rowIndex);
}
this.DeleteRows(sheet, rowCount+rowIndex);
range = sheet.get_Range(cellID, missing);
range = range.get_Resize(rowCount, colCount);
range.Value2 = array;
}
///
/// 將DataTable資料匯出到Excel(固定)
///
/// DataTable
/// 插入資料的起始儲存格
public void DataTableToExcel2(System.Data.DataTable dt, string cellID)
{
int rowCount = dt.Rows.Count; //DataTable行數
int colCount = dt.Columns.Count; //DataTable列數
int iRow;
int iCol;
//利用二維數組批量寫入
string[,] array = new string[rowCount,colCount];
for (iRow = 0; iRow < rowCount; iRow++)
{
for (iCol = 0; iCol < colCount; iCol++)
{
array[iRow,iCol] = dt.Rows[iRow][iCol].ToString();
}
}
range = sheet.get_Range(cellID, missing);
range = range.get_Resize(rowCount, colCount);
range.Value2 = array;
}
///
/// 輸出產生的Excel, Html檔案
///
public void OutputFile()
{
if (this.excelFile == null)
throw new Exception("沒有指定Excel輸出檔案路徑!");
if (this.htmlFile == null)
throw new Exception("沒有指定Htmll輸出檔案路徑!");
try
{
book.SaveAs(excelFile, missing, missing, missing, missing, missing,
Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing,missing);
book.SaveAs(htmlFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing,
Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
}
catch (Exception e)
{
throw e;
}
finally
{
this.Dispose();
}
}
///
/// 在工作表中插入行,並調整其他行以留出空間
///
/// 當前工作表
/// 欲插入的行索引
private void InsertRows(Excel.Worksheet sheet, int rowIndex)
{
Range r = (Excel.Range)sheet.Rows[rowIndex, missing];
//object Range.Insert(object shift, object copyorigin);
//shift: Variant類型,可選。指定儲存格的調整方式。可以為下列 XlInsertShiftDirection 常量之一:
//xlShiftToRight 或 xlShiftDown。如果省略該參數,Microsoft Excel 將根據地區形狀確定調整方式。
r.Insert(Excel.XlInsertShiftDirection.xlShiftDown, missing);
}
///
/// 在工作表中刪除行
///
/// 當前工作表
/// 欲刪除的行索引
private void DeleteRows(Excel.Worksheet sheet, int rowIndex)
{
Range r = (Range)sheet.Rows[rowIndex, missing];
r.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
}
///
/// 退出Excel,並且釋放調用的COM資源
///
private void Dispose()
{
book.Close(missing, missing, missing);
app.Workbooks.Close();
app.Quit();
if(range != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
}
if(sheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
sheet = null;
}
if(book != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
book = null;
}
if(app != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
GC.Collect();
this.KillExcelProcess();
}
///
/// 結束Excel進程
///
private void KillExcelProcess()
{
DateTime startTime;
Process[] processes = Process.GetProcessesByName("Excel");
//得不到Excel進程ID,暫時只能判斷進程啟動時間
foreach (Process process in processes)
{
startTime = process.StartTime;
if(startTime > beforeTime && startTime < afterTime)
process.Kill();
}
}
}
}