excel操作类

UI调用

--------------------------------------------

public partial class OledbTool : Form
{
public static string DbConnectionString = ConfigurationManager.ConnectionStrings["DB"].ToString();
private DataTable dt;
public OledbTool()
{
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e)
{
var folderBrowser = new FolderBrowserDialog();
var result= folderBrowser.ShowDialog();
if (result == DialogResult.OK)
{
txtExcelPath.Text = folderBrowser.SelectedPath;
}
}

private void button1_Click(object sender, EventArgs e)
{
var folderPath = txtExcelPath.Text;
string[] filePathS = GetAllFilePaths(folderPath);
//var _t=0;

foreach (var excelFile in filePathS)
{
var excelHelper = new ExcelHelper();
excelHelper.OpenExcel(excelFile);

var excelOledbHelper = new ExcelOledbHelper(excelFile);
excelOledbHelper.OpenExcelUseOledb("YES","1");
var firstSheet = excelHelper.GetFirstSheet();
var firstSheetName = firstSheet.Name;
var startRow = excelHelper.GetStartRowIndex(firstSheetName);
var startColumn = excelHelper.GetStartColumnIndex(firstSheetName, startRow);
var rowCount = firstSheet.UsedRange.Cells.Rows.Count;
dt= excelOledbHelper.GetData(firstSheetName, startRow, rowCount);
dgv.DataSource = dt;
excelHelper.CloseWorkbook();
//var _t = 0;
//object[,] columns = excelHelper.GetData(firstSheetName, startRow, startColumn);
//List<string> columnNames=new List<string>();
//foreach (var column in columns)
//{
// if (column == null)
// {
// columnNames.Add("");
// }
// else
// {
// columnNames.Add(column.ToString());
// }
//}
////var _t = 0;
//SqlHelper.BulkInsert(DbConnectionString, "媒体列表", dt, columnNames.ToArray());
//var _t = 0;
}

 

}

private string[] GetAllFilePaths(string folderPath)
{
var filePaths = new List<string>();
filePaths.AddRange(Directory.GetFiles(folderPath));
string[] folderPaths = Directory.GetDirectories(folderPath);
if (folderPaths.Length > 0)
{
foreach (var folder in folderPaths)
{
filePaths.AddRange(GetAllFilePaths(folder));
}
}
return filePaths.OrderBy(i => i.ToLower()).ToArray();
}

private void button3_Click(object sender, EventArgs e)
{
ExcelHelper excelHelper=new ExcelHelper();
string path = @"D:\SampleData\TestExcels\export\1.xls";
excelHelper.OpenExcel(path);
var sheetName= excelHelper.GetFirstSheet().Name;
//excelHelper.FormatAllCellsToText(sheetName);
excelHelper.WriteRange(sheetName, 2, 1, dt);
excelHelper.Save(path);
excelHelper.CloseWorkbook();
MessageBox.Show("complete!");
}
}

 

 

 

ExcelHelper

-------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using DataTable = System.Data.DataTable;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace OledbTool
{
public class ExcelHelper
{
private static Application _app;
private _Workbook _workbook;
private _Worksheet _worksheet;
private string _excelPath;
private OleDbDataAdapter adapter;
private OleDbConnection conn;

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

public string ExcelPath
{
get
{
return _excelPath;
}
}

public ExcelHelper()
{

}

/// <summary>
/// open excel
/// </summary>
/// <param name="filePath">file path</param>
public void OpenExcel(string filePath)
{
_excelPath = filePath;
if (_app == null)
{
_app = new Application();
}
_app.Visible = false;
_app.UserControl = true;
object missing = System.Reflection.Missing.Value;
_workbook = _app.Application.Workbooks.Open(filePath, missing, true, missing, missing, missing,
missing, missing, missing, true, missing, missing, missing, missing, missing);
_worksheet = GetFirstSheet();
}

/// <summary>
/// close workbook
/// </summary>
public void CloseWorkbook()
{
_workbook.Close(false);
_workbook = null;
_excelPath = string.Empty;
}

/// <summary>
/// dispose excel application
/// </summary>
public void QuitExcelApp()
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(_worksheet);
_worksheet = null;
if (_workbook != null)
{
_workbook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_workbook);
_workbook = null;
}

_app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(_app);
_app = null;

//_app.DisplayAlerts = false;//不显示提示框
//_app.Quit();
//KillSpecialExcel(_app);
//_app = null;

}
catch (System.Exception ex)
{

}
finally
{
foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("Excel"))
pro.Kill();
}
}

public void KillSpecialExcel(Application excelApp)
{
try
{
if (excelApp != null)
{
int lpdwProcessId;
GetWindowThreadProcessId(new IntPtr(excelApp.Hwnd), out lpdwProcessId);
Process p = System.Diagnostics.Process.GetProcessById(lpdwProcessId);

p.Kill();

}
}
catch (Exception ex)
{
Console.WriteLine("Delete Excel Process Error:" + ex.Message);
throw new Exception("Delete Excel Process Error:" + ex.Message);
}

}
/// <summary>
/// save workbook
/// </summary>
/// <param name="path">excel path</param>
public void Save(string path)
{
_workbook.SaveCopyAs(path);
}

/// <summary>
/// save as workbook
/// </summary>
/// <param name="path">excel path</param>
public void SaveAs(string path)
{
_workbook.SaveAs(path);
}

/// <summary>
/// get worksheet by name
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <returns></returns>
public Worksheet GetWorkSheetByName(string sheetName)
{
//Worksheet worksheet = (Worksheet)_workbook.Worksheets.get_Item(1);

foreach (var sheet in _workbook.Worksheets)
{
var workSheet = (Worksheet)sheet;
if (workSheet.Name.ToLower() == sheetName.ToLower())
{
return workSheet;
}
}
return null;
}

/// <summary>
/// delete row
/// </summary>
/// <param name="sheetName">name of sheet</param>
/// <param name="rowIndex">in</param>
/// <param name="rowCount">count of rows</param>
public void DeleteRows(string sheetName, int rowIndex, int rowCount)
{
var sheet = GetWorkSheetByName(sheetName);
object missing = System.Reflection.Missing.Value;
//var range = (Range)sheet.Rows[rowIndex, missing];
var range = (Range)sheet.Range[sheet.Cells[rowIndex, 1], sheet.Cells[rowIndex + rowCount - 1, 1]];
range.EntireRow.Delete(XlDeleteShiftDirection.xlShiftUp);
//_workbook.Save();
}

/// <summary>
/// format all cells to text
/// </summary>
public void FormatAllCellsToText(string sheetName)
{
var sheet = (Worksheet)GetWorkSheetByName(sheetName);
int rowCount = sheet.UsedRange.Cells.Rows.Count;
int columnCount = sheet.UsedRange.Cells.Columns.Count;
var startRowIndex = GetStartRowIndex(sheetName);
var startColumnIndex = GetStartColumnIndex(sheetName, startRowIndex);
Range range = sheet.Range[sheet.Cells[startRowIndex, startColumnIndex], sheet.Cells[startRowIndex + rowCount - 1, startColumnIndex + columnCount - 1]];
range.NumberFormatLocal = "@";
}

/// <summary>
/// get data from excel sheet
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <param name="startRow">start index of row</param>
/// <param name="startColumn">start index of column</param>
/// <returns></returns>
public object[,] GetData(string sheetName, int startRow, int startColumn)
{
Worksheet ws = (Worksheet)GetWorkSheetByName(sheetName);
_worksheet = ws;
int rowCount = ws.UsedRange.Cells.Rows.Count;
int columnCount = ws.UsedRange.Cells.Columns.Count;
Range range = ws.Range[ws.Cells[startRow, startColumn], ws.Cells[startRow + rowCount - 2, startColumn + columnCount - 1]];
object[,] arryItem = (object[,])range.Value2; //get range's value
return arryItem;
}


/// <summary>
/// get data from excel sheet
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <param name="startRow">start index of row</param>
/// <param name="startColumn">start index of column(start 1)</param>
/// <param name="rowCount">count of rows</param>
/// <returns></returns>
public object[,] GetData(string sheetName, int startRow, int startColumn, int rowCount)
{
Worksheet ws = (Worksheet)GetWorkSheetByName(sheetName);
_worksheet = ws;
int columnCount = ws.UsedRange.Cells.Columns.Count;
Range range = ws.Range[ws.Cells[startRow, startColumn], ws.Cells[startRow + rowCount - 1, startColumn + columnCount - 1]];
object[,] arryItem = (object[,])range.Value2; //get range's value
return arryItem;
}


/// <summary>
/// Get first sheet object
/// </summary>
/// <returns></returns>
public Worksheet GetFirstSheet()
{
return (Worksheet)_workbook.Worksheets.get_Item(1);
}

/// <summary>
/// Get current workbook
/// </summary>
/// <returns></returns>
public _Workbook GetWorkbook()
{
return _workbook;
}

/// <summary>
/// Get start row(have data)
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <returns></returns>
public int GetStartRowIndex(string sheetName)
{
Worksheet ws = (Worksheet)GetWorkSheetByName(sheetName);
for (var i = 1; i <= 50000; i++)
{
Range range = ws.Range[ws.Cells[i, 1], ws.Cells[i, 1]];
if (range.Value2 != null)
{
return i;
}
}
return 1;

}

/// <summary>
/// Get start row(have data)
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <param name="value">cell value</param>
/// <returns></returns>
public int GetStartRowIndexByValue(string sheetName, string value)
{
var ws = (Worksheet)GetWorkSheetByName(sheetName);
for (var i = 1; i <= 50000; i++)
{
var range = ws.Range[ws.Cells[i, 1], ws.Cells[i, 1]];
if (range.Value2 == value)
{
return i;
}
}
return 1;
}

/// <summary>
/// Get start column(have data)
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <param name="startRowIndex">index of start row</param>
/// <returns></returns>
public int GetStartColumnIndex(string sheetName, int startRowIndex)
{
var ws = (Worksheet)GetWorkSheetByName(sheetName);
for (var i = 1; i <= 50000; i++)
{
Range range = ws.Range[ws.Cells[startRowIndex, i], ws.Cells[startRowIndex, i]];
if (range.Value2 != null)
{
return i;
}
}
return 1;
}


/// <summary>
/// Get total row count
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <returns></returns>
public int GetTotalRowCount(string sheetName)
{
var ws = (Worksheet)GetWorkSheetByName(sheetName);
return ws.UsedRange.Cells.Rows.Count;
}

/// <summary>
/// Get Column Count
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <returns></returns>
public int GetColumnCount(string sheetName)
{
var ws = (Worksheet)GetWorkSheetByName(sheetName);
return ws.UsedRange.Cells.Columns.Count;
}


public void WriteRange(string sheetName, int startRowIndex, int startColumnIndex, object[,] value)
{

}


public void WriteRange(string sheetName, int startRowIndex, int startColumnIndex, DataTable dt)
{
var rowCount = dt.Rows.Count;
var columnCount = dt.Columns.Count;
var value = new object[rowCount, columnCount];
var sheet = (Worksheet)GetWorkSheetByName(sheetName);
Range range = sheet.Range[sheet.Cells[startRowIndex, startColumnIndex], sheet.Cells[startRowIndex + rowCount - 1, startColumnIndex + columnCount - 1]];

for (var i = 0; i < dt.Rows.Count; i++)
{
for (var j = 0; j < dt.Columns.Count; j++)
{
value[i, j] = dt.Rows[i][j].ToString();
}
}
range.Value2 = value;
}
}
}

------------------------------------------------------

ExcelExport

using System.Collections.Generic;
using Microsoft.Office.Interop.Excel;
using System.Web;
using System.IO;
using System;
using System.Reflection;
using System.Data;

namespace OledbTool
{
public class ExcelExport
{
private string TemplateFolderName = "";
private string TemplateFileName = "";
private string ExportFolderName = "";
private string ExportFileName = "";
private string templatePath = "";
private string exportPath = "";
private int state = 0;
private string fartherPath = "";
private string exportFilePath = "";
Application app = new Application();
private _Workbook workbook;
private string exportInfo = "";
public bool IsExist = false;
/// <summary>
/// 构造函数,为字段赋值,另调用判断模版文件、导出文件夹是否存在并初始化workbook的函数
/// </summary>
/// <param name="TemplateFolderName">模版文件夹名</param>
/// <param name="TemplateFileName">模版文件名</param>
/// <param name="ExportFolderName">导出文件夹名</param>
/// <param name="ExportFileName">导出文件名</param>
/// <param name="FartherPath">根路径</param>
/// <param name="reportName">报表名</param>
public ExcelExport(string TemplateFolderName, string TemplateFileName, string ExportFolderName, string ExportFileName, string FartherPath, string reportName)
{
this.TemplateFolderName = TemplateFolderName;
this.TemplateFileName = TemplateFileName;
this.ExportFolderName = ExportFolderName;
this.ExportFileName = ExportFileName;
this.fartherPath = FartherPath;
Init(reportName);
InitWorkbook();
}

/// <summary>
/// 构造函数,为字段赋值,另调用判断模版文件、导出文件夹是否存在并初始化workbook的函数
/// </summary>
/// <param name="TemplateFolderName">模版文件夹名</param>
/// <param name="TemplateFileName">模版文件名</param>
/// <param name="ExportFolderName">导出文件夹名</param>
/// <param name="ExportFileName">导出文件名</param>
/// <param name="FartherPath">根路径</param>
/// <param name="reportName">报表名</param>
public ExcelExport(string TemplateFolderName, string TemplateFileName, string ExportFolderName, string ExportFileName, string FartherPath, string ExportFilePath, string reportName)
{
this.TemplateFolderName = TemplateFolderName;
this.TemplateFileName = TemplateFileName;
this.ExportFolderName = ExportFolderName;
this.ExportFileName = ExportFileName;
this.fartherPath = FartherPath;
this.exportFilePath = ExportFilePath;
Init_New(reportName);
if (IsExist == false)
InitWorkbook();
}

/// <summary>
/// 判断模版文件、导出文件夹是否存在
/// </summary>
/// <param name="reportName">报表名</param>
void Init(string reportName)
{
string mainPath = fartherPath;
templatePath = mainPath + TemplateFolderName + "\\" + TemplateFileName;
if (!File.Exists(templatePath))
state = 1;

Random r = new Random(DateTime.Now.Second);
string exportFolderPath = mainPath + ExportFolderName;
if (!Directory.Exists(exportFolderPath))
state = 2;
do
{
string random = r.Next(10000).ToString();
exportPath = exportFolderPath + "\\" + reportName;
} while (File.Exists(exportPath));

switch (state)
{
case 1:
exportInfo = "The template file can not be found.";
break;
case 2:
exportInfo = "The export folder can not be found.";
break;
}
}

/// <summary>
/// 判断模版文件、导出文件夹是否存在
/// </summary>
/// <param name="reportName">报表名</param>
void Init_New(string reportName)
{
string mainPath = fartherPath;
templatePath = mainPath + TemplateFolderName + "\\" + TemplateFileName;
if (!File.Exists(templatePath))
state = 1;

Random r = new Random(DateTime.Now.Second);
string exportFolderPath = exportFilePath;
if (!Directory.Exists(exportFolderPath))
state = 2;
//do
//{
// string random = r.Next(10000).ToString();
// exportPath = exportFolderPath + "\\" + reportName;
//} while (File.Exists(exportPath));


string random = r.Next(10000).ToString();
exportPath = exportFolderPath + reportName;

switch (state)
{
case 1:
exportInfo = "The template file can not be found.";
break;
case 2:
exportInfo = "The export folder can not be found.";
break;
}

//判断是否已经生成相关文件
if (File.Exists(exportPath))
IsExist = true;
else
{
IsExist = false;
}


}

/// <summary>
/// 初始化workbook
/// </summary>
void InitWorkbook()
{
//Build a new Excel.Application
if (app == null)
{
state = 0;
}
app.Visible = false;
app.UserControl = true;
Workbooks workbooks = app.Workbooks;
workbook = workbooks.Add(templatePath);
}
/// <summary>
/// 获取workbook
/// </summary>
/// <returns>return workbook</returns>
public _Workbook GetWorkbook()
{
return workbook;
}

/// <summary>
/// ExecuteExport
/// </summary>
/// <param name="workbook">workbook</param>
/// <param name="worksheets">workbook包含的所有worksheet</param>
/// <returns>return 导出文件路径</returns>
public string ExecuteExport()
{
workbook.RefreshAll();
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
ExcelOperate excelOperate = new ExcelOperate();
workbook.SaveAs(exportPath, XlFileFormat.xlOpenXMLWorkbookMacroEnabled, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
excelOperate.Dispose(worksheet, workbook, app);
return exportPath;
}
/// <summary>
/// 往Excel中特定区域输入值
/// </summary>
/// <param name="sheet">one sheet</param>
/// <param name="array">Excel中需要填充的值</param>
/// <param name="x">Excel中单元格横坐标</param>
/// <param name="y">Excel中单元格纵坐标</param>
/// <param name="dataFormat">数据格式</param>
public void DrawArray(object sheet, Array array, int x, int y, string dataFormat)
{
try
{
//Normalize(array);
int startRowIndex = 0;
int rows = array == null ? 0 : array.GetLength(0);
int row = y;
Range startCell = (Range)((Worksheet)sheet).Cells[y, x];
Range outputRange = startCell;
//Array arr = GetSubDataTableArray(array, startRowIndex, (row + rows > MaxRow) ? (MaxRow - row + 1) : rows);
Array arr = array;
if (arr != null && arr.GetLength(0) > 0)
{
outputRange = startCell.get_Resize(arr.GetLength(0), arr.GetLength(1));
if (!string.IsNullOrEmpty(dataFormat))
{
outputRange.NumberFormat = dataFormat;
}
startRowIndex = arr.GetLength(0);
outputRange.Value2 = arr;
}
}
catch (Exception exp)
{
throw new Exception(exp.Message, exp);
}
}
/// <summary>
/// 执行VBA初始化
/// </summary>
/// <returns></returns>
public object RunMacro()
{
Workbook wb = workbook as Workbook;
var oRunArgs = new object[]
{
"'" + wb.Name + "'!Init"
};
object objRtn;
objRtn = app.GetType().InvokeMember("Run",
BindingFlags.Default |
BindingFlags.InvokeMethod,
null,
app,
oRunArgs
);

return objRtn;
}
/// <summary>
/// 填充单元格
/// </summary>
/// <param name="sheet">one sheet</param>
/// <param name="obj">填充的数据</param>
/// <param name="x">Excel中横轴位置</param>
/// <param name="y">Excel中纵轴位置</param>
public void DrawCell(object sheet, string obj, int x, int y)
{
string[,] array = new string[,] { { (string)obj } };
DrawArray(sheet, array, x, y, null);
}
/// <summary>
/// 填充单元格
/// </summary>
/// <param name="sheet">要填充数据的sheet</param>
/// <param name="obj">要填充的数据</param>
/// <param name="x">横轴位置</param>
/// <param name="y">纵轴位置</param>
public void DrawCell(object sheet, double obj, int x, int y)
{
var array = new[,] { { obj } };
DrawArray(sheet, array, x, y, null);
}
/// <summary>
/// 数据转换(先将泛型数组转换为DataTable,再将此DataTable转换为Excel可识别的Array)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="results">T类型数组</param>
/// <param name="isKeepHeader">是否有表头</param>
/// <param name="necessaryColumns">必要的列名集合</param>
/// <returns>return Array</returns>
public Array ResultTypeToArray<T>(T[] results, bool isKeepHeader, List<string> necessaryColumns)
{
System.Data.DataTable resultTable = ConvertResultTypeToDataTable(results);
return DataTableToArray(resultTable, isKeepHeader, necessaryColumns);
}
/// <summary>
/// 将泛型数组转换为DataTable
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="results">泛型数组</param>
/// <returns>return DataTable</returns>
public System.Data.DataTable ConvertResultTypeToDataTable<T>(T[] results)
{
System.Data.DataTable resultTable = new System.Data.DataTable();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo info in properties)
{
if (info.CanRead && info.Name != "ExtensionData")
{
resultTable.Columns.Add(info.Name, info.PropertyType);
}
}
foreach (T result in results)
{
DataRow dr = resultTable.NewRow();
foreach (PropertyInfo info in properties)
{
if (info.CanRead && info.Name != "ExtensionData")
{
dr[info.Name] = info.GetValue(result, null);
}
}
resultTable.Rows.Add(dr);
}
return resultTable;
}
/// <summary>
/// 将DataTable转换为Excel可识别的Array
/// </summary>
/// <param name="sourceDataTable">源DataTable</param>
/// <param name="isKeepHeader">是否要表头</param>
/// <param name="necessaryColumns">必要的列名集合</param>
/// <returns>return Array</returns>
public Array DataTableToArray(System.Data.DataTable sourceDataTable, bool isKeepHeader, List<string> necessaryColumns)
{
int rowCount = sourceDataTable.Rows.Count;
int colCount = sourceDataTable.Columns.Count;
object[,] targetArray;
int factor = 0;
if (isKeepHeader)
{
targetArray = new object[rowCount + 1, necessaryColumns == null ? colCount : necessaryColumns.Count];

for (int i = 0; i < colCount; i++)
{
if (necessaryColumns == null || necessaryColumns.Contains(sourceDataTable.Columns[i].Caption))
{
targetArray[0, factor++] = sourceDataTable.Columns[i].Caption;
}
}

for (int i = 0; i < rowCount; i++)
{
factor = 0;
for (int j = 0; j < colCount; j++)
{
if (necessaryColumns == null || necessaryColumns.Contains(sourceDataTable.Columns[j].Caption))
targetArray[i + 1, factor++] = sourceDataTable.Rows[i][j];
}
}
}
else
{
targetArray = new object[rowCount, necessaryColumns == null ? colCount : necessaryColumns.Count];
for (int i = 0; i < rowCount; i++)
{
factor = 0;
for (int j = 0; j < colCount; j++)
{
if (necessaryColumns == null || necessaryColumns.Contains(sourceDataTable.Columns[j].Caption))
targetArray[i, factor++] = sourceDataTable.Rows[i][j];
}
}
}

return targetArray;
}
/// <summary>
/// 根据sheet名获取指定的sheet
/// </summary>
/// <param name="sheetName">sheet名</param>
/// <returns>return Worksheet</returns>
public object GetSheetByName(string sheetName)
{
if (workbook == null || string.IsNullOrEmpty(sheetName))
{
return null;
}

Workbook wb = workbook as Workbook;
foreach (Worksheet sheet in wb.Sheets)
{
if (string.Compare(sheet.Name, sheetName, StringComparison.CurrentCultureIgnoreCase) == 0)
{
return sheet;
}
}

return null;
}
/// <summary>
/// 隐藏列
/// </summary>
/// <param name="sheet">sheet</param>
/// <param name="columnIndex">列索引</param>
/// <param name="columnCount">列数</param>
public void HideColumns(object sheet, int columnIndex, int columnCount)
{
Worksheet ws = sheet as Worksheet;
if (ws == null)
{
return;
}

Range range = ws.Cells[1, columnIndex] as Range;
if (range != null)
{
range = range.get_Resize(1, columnCount);
range.EntireColumn.Hidden = true;
}
}
/// <summary>
/// 隐藏行
/// </summary>
/// <param name="sheet">sheet</param>
/// <param name="rowIndex">行索引</param>
/// <param name="rowCount">行数</param>
public void HideRows(object sheet, int rowIndex, int rowCount)
{
Worksheet ws = sheet as Worksheet;
if (ws == null)
{
return;
}

Range range = ws.Cells[rowIndex, 1] as Range;
if (range != null)
{
range = range.get_Resize(rowCount, 1);
range.EntireRow.Hidden = true;
}
}
/// <summary>
/// HideSheet
/// </summary>
/// <param name="sheet">工作表</param>
/// <param name="isVeryHide">是否高级隐藏(值为true,则此工作表只能在VBA里打开)</param>
public void HideSheet(object sheet, bool isVeryHide)
{
Worksheet ws = sheet as Worksheet;
if (ws == null)
{
return;
}

if (isVeryHide)
ws.Visible = XlSheetVisibility.xlSheetVeryHidden;
else
ws.Visible = XlSheetVisibility.xlSheetHidden;
}
}

/// <summary>
/// ExcelOperate
/// </summary>
class ExcelOperate
{
private object mValue = System.Reflection.Missing.Value;

/// <summary>
/// Merge Cell
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">StartCell</param>
/// <param name="objEndCell">EndCell</param>
public void Merge(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).Merge(mValue);
}
/// <summary>
/// set font size
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="strStartCell">StartCell</param>
/// <param name="strEndCell">EndCell</param>
/// <param name="intFontSize">FontSize</param>
public void SetFontSize(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, int intFontSize)
{
CurSheet.get_Range(objStartCell, objEndCell).Font.Size = intFontSize.ToString();
}

/// <summary>
/// type landscape
/// </summary>
/// <param name="CurSheet">worksheet</param>
public void xlLandscape(Microsoft.Office.Interop.Excel._Worksheet CurSheet)
{
CurSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;

}
/// <summary>
/// type Portrait
/// </summary>
/// <param name="CurSheet">Worksheet</param>
public void xlPortrait(Microsoft.Office.Interop.Excel._Worksheet CurSheet)
{
CurSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait;
}

/// <summary>
/// insert cell
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="Cell">cell ex. Cells[1,1]</param>
/// <param name="objValue">words\numbers etc.</param>
public void WriteCell(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objCell, object objValue)
{
CurSheet.get_Range(objCell, mValue).Value2 = objValue;
}

/// <summary>
/// insert something
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="StartCell">startcell</param>
/// <param name="EndCell">endcell</param>
/// <param name="objValue">words\numbers etc.</param>
public void WriteRange(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, object objValue)
{
CurSheet.get_Range(objStartCell, objEndCell).Value2 = objValue;
}

/// <summary>
/// merge cells,and insert words
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">start cell</param>
/// <param name="objEndCell">end cell</param>
/// <param name="objValue">words/numbers etc.</param>
public void WriteAfterMerge(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, object objValue)
{
CurSheet.get_Range(objStartCell, objEndCell).Merge(mValue);
CurSheet.get_Range(objStartCell, mValue).Value2 = objValue;

}

/// <summary>
/// set formula for a cell
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objCell">cell</param>
/// <param name="strFormula">formula</param>
public void SetFormula(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objCell, string strFormula)
{
CurSheet.get_Range(objCell, mValue).Formula = strFormula;
}

/// <summary>
/// auto wrap
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">start cell</param>
/// <param name="objEndCell">end cell</param>
public void AutoWrapText(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).WrapText = true;
}

/// <summary>
/// set color
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">start color</param>
/// <param name="objEndCell">end color</param>
/// <param name="clrColor">color</param>
public void SetColor(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, System.Drawing.Color clrColor)
{
CurSheet.get_Range(objStartCell, objEndCell).Font.Color = System.Drawing.ColorTranslator.ToOle(clrColor);
}

/// <summary>
/// set background-color
/// </summary>
/// <param name="CurSheet"></param>
/// <param name="objStartCell"></param>
/// <param name="objEndCell"></param>
/// <param name="clrColor"></param>
public void SetBgColor(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, System.Drawing.Color clrColor)
{
CurSheet.get_Range(objStartCell, objEndCell).Interior.Color = System.Drawing.ColorTranslator.ToOle(clrColor);
}

/// <summary>
/// set font name
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">start cell</param>
/// <param name="objEndCell">end cell</param>
/// <param name="fontname">font name</param>
public void SetFontName(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, string fontname)
{
CurSheet.get_Range(objStartCell, objEndCell).Font.Name = fontname;
}

/// <summary>
/// set font bold
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell"></param>
/// <param name="objEndCell"></param>
public void SetBold(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).Font.Bold = true;
}

/// <summary>
/// set all border around has normal frame
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">StartCell</param>
/// <param name="objEndCell">EndCell</param>
public void SetBorderAll(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
CurSheet.get_Range(objStartCell, objEndCell).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

}

/// <summary>
/// Set Horizontal Align Center
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">StartCell</param>
/// <param name="objEndCell">EndCell</param>
public void SetHAlignCenter(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
}

/// <summary>
/// Set Horizontal Align Left
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">StartCell</param>
/// <param name="objEndCell">EndCell</param>
public void SetHAlignLeft(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}

/// <summary>
/// Set Horizontal Align Right
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">StartCell</param>
/// <param name="objEndCell">EndCell</param>
public void SetHAlignRight(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell)
{
CurSheet.get_Range(objStartCell, objEndCell).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
}

/// <summary>
/// SetNumberFormat
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">StartCell</param>
/// <param name="objEndCell">EndCell</param>
/// <param name="strNF">such as "#,##0.00"</param>
public void SetNumberFormat(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, string strNF)
{
CurSheet.get_Range(objStartCell, objEndCell).NumberFormat = strNF;
}

/// <summary>
/// SetColumnWidth
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="strColID">Column ID</param>
/// <param name="dblWidth">Width</param>
public void SetColumnWidth(Microsoft.Office.Interop.Excel._Worksheet CurSheet, string strColID, double dblWidth)
{
((Microsoft.Office.Interop.Excel.Range)CurSheet.Columns.GetType().InvokeMember("Item", System.Reflection.BindingFlags.GetProperty, null, CurSheet.Columns, new object[] { (strColID + ":" + strColID).ToString() })).ColumnWidth = dblWidth;
}

/// <summary>
/// SetColumnWidth
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">Start Cell</param>
/// <param name="objEndCell">End Cell</param>
/// <param name="dblWidth">Width</param>
public void SetColumnWidth(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, double dblWidth)
{
CurSheet.get_Range(objStartCell, objEndCell).ColumnWidth = dblWidth;
}


/// <summary>
/// SetRowHeight
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objStartCell">Start Cell</param>
/// <param name="objEndCell">End Cell</param>
/// <param name="dblHeight">Height</param>
public void SetRowHeight(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objStartCell, object objEndCell, double dblHeight)
{
CurSheet.get_Range(objStartCell, objEndCell).RowHeight = dblHeight;
}


/// <summary>
/// AddHyperLink
/// </summary>
/// <param name="CurSheet">Worksheet</param>
/// <param name="objCell">Cell</param>
/// <param name="strAddress">Address</param>
/// <param name="strTip">ScreenTip</param>
/// <param name="strText">Text to Display</param>
public void AddHyperLink(Microsoft.Office.Interop.Excel._Worksheet CurSheet, object objCell, string strAddress, string strTip, string strText)
{
CurSheet.Hyperlinks.Add(CurSheet.get_Range(objCell, objCell), strAddress, mValue, strTip, strText);
}

/// <summary>
/// Save as xls file
/// </summary>
/// <param name="CurBook">Workbook</param>
/// <param name="strFilePath">File path</param>
public void Save(Microsoft.Office.Interop.Excel._Workbook CurBook, string strFilePath)
{
CurBook.SaveCopyAs(strFilePath);
}

/// <summary>
/// Save xls file
/// </summary>
/// <param name="CurBook">Workbook</param>
/// <param name="strFilePath">File path</param>
public void SaveAs(Microsoft.Office.Interop.Excel._Workbook CurBook, string strFilePath)
{
CurBook.SaveAs(strFilePath, mValue, mValue, mValue, mValue, mValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, mValue, mValue, mValue, mValue, mValue);
}

/// <summary>
/// Save as html file
/// </summary>
/// <param name="CurBook">Workbook</param>
/// <param name="strFilePath">File path</param>
public void SaveHtml(Microsoft.Office.Interop.Excel._Workbook CurBook, string strFilePath)
{
CurBook.SaveAs(strFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml, mValue, mValue, mValue, mValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, mValue, mValue, mValue, mValue, mValue);
}

/// <summary>
/// Dispose memory
/// </summary>
public void Dispose(Microsoft.Office.Interop.Excel._Worksheet CurSheet, Microsoft.Office.Interop.Excel._Workbook CurBook, Microsoft.Office.Interop.Excel._Application CurExcel)
{
List<_Worksheet> curSheets = new List<_Worksheet>();
curSheets.Add(CurSheet);
Dispose(curSheets, CurBook, CurExcel);
}
/// <summary>
/// Dispose
/// </summary>
/// <param name="CurSheets">Worksheet</param>
/// <param name="CurBook">Workbook</param>
/// <param name="CurExcel">Excel Application</param>
public void Dispose(List<Microsoft.Office.Interop.Excel._Worksheet> CurSheets, Microsoft.Office.Interop.Excel._Workbook CurBook, Microsoft.Office.Interop.Excel._Application CurExcel)
{
try
{
foreach (_Worksheet worksheet in CurSheets)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
}
CurSheets = null;
CurBook.Close(false, mValue, mValue);
System.Runtime.InteropServices.Marshal.ReleaseComObject(CurBook);
CurBook = null;

CurExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(CurExcel);
CurExcel = null;

GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (System.Exception ex)
{
//HttpContext.Current.Response.Write("Error while dispose memory:" + ex);
}
finally
{
foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("Excel"))
//if (pro.StartTime < DateTime.Now)
pro.Kill();
}
System.GC.SuppressFinalize(this);
}
}
}

------------------------------------------------------------

ExcelOledbHelper

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

namespace OledbTool
{
public class ExcelOledbHelper
{
private string _excelPath;
private OleDbConnection _conn;

public ExcelOledbHelper(string filePath)
{
_excelPath = filePath;
}

/// <summary>
/// use OLEDB open excel
/// </summary>
public void OpenExcelUseOledb(string hdr, string imex)
{
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _excelPath + ";Extended Properties='Excel 12.0;HDR=" + hdr + ";IMEX=" + imex + "'";
_conn = new OleDbConnection(conStr);
_conn.Open();
}

/// <summary>
/// close oledb connection
/// </summary>
public void CloseExcelOledbConnection()
{
_conn.Close();
_conn.Dispose();
}

/// <summary>
/// get all data from excel sheet,convert datatable
/// </summary>
/// <param name="sheetName">sheet name</param>
/// <param name="startRow">start index of row(start 0)</param>
/// <param name="rowCount">count of rows</param>
/// <returns></returns>
public System.Data.DataTable GetData(string sheetName, int startRow, int rowCount)
{
var comStr = "SELECT * FROM [" + sheetName + "$]";
var oleDbDataAdapter = new OleDbDataAdapter(comStr, _conn);
var ds = new DataSet();
oleDbDataAdapter.Fill(ds, startRow, rowCount, "a");
oleDbDataAdapter.Dispose();
if (ds.Tables.Count > 0)
{
return ds.Tables[0];
}
else
{
return null;
}
}
}
}

-----------------------------------------------------------

SqlHelper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Configuration;
using Microsoft.SqlServer.Server;

namespace OledbTool
{
public class SqlHelper
{

/// <summary>
/// 构造函数
/// </summary>
static SqlHelper()
{
//var im = new Impersonator(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["DomainName"],
//ConfigurationManager.AppSettings["Password"]);
}
/// <summary>
/// Execute DataSet
/// </summary>
/// <param name="connectionString">连接数据库的字符串</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="commandParameters">Command Parameters</param>
/// <returns>return DataSet</returns>
public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{

using (var cmd = new SqlCommand())
{
try
{
using (var conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
cmd.CommandTimeout = 900;
var sda = new SqlDataAdapter(cmd);
var ds = new DataSet();
sda.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
catch (Exception ex)
{

throw;
}
}
}
/// <summary>
/// Execute DataSet
/// </summary>
/// <param name="connectionString">连接数据库的字符串</param>
/// <param name="cmdType">Command type</param>
/// <param name="sqlCommand">Command Text</param>
/// <returns>return DataSet</returns>
public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, SqlCommand sqlCommand)
{
try
{
using (var conn = new SqlConnection(connectionString))
{
PrepareCommand(sqlCommand, conn, null, cmdType);
var sda = new SqlDataAdapter(sqlCommand);
var ds = new DataSet();
sda.Fill(ds);
sqlCommand.Parameters.Clear();
sda.Dispose();
return ds;
}
}
catch (Exception)
{
throw;
}
finally
{
if (sqlCommand != null) sqlCommand.Dispose();
}

}
/// <summary>
/// ExecuteNonQuery
/// </summary>
/// <param name="connectionString">连接数据库的字符串</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="commandParameters">Command Parameters</param>
/// <returns>return int</returns>
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
catch (SqlException ex)
{
throw ex;
}
}
}
/// <summary>
/// ExecuteNonQuery
/// </summary>
/// <param name="connection">SqlConnection object</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="commandParameters">Command Parameters</param>
/// <returns>return int</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
catch (SqlException ex)
{
throw ex;
}
}
}
/// <summary>
/// ExecuteNonQuery
/// </summary>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="commandParameters">Command Parameters</param>
/// <returns>return int</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
using (SqlCommand cmd = new SqlCommand())
{
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// ExecuteReader
/// </summary>
/// <param name="connectionString">连接数据库的字符串</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="readerCallback">reader Callback</param>
/// <param name="commandParameters">Command Parameters</param>
public static void ExecuteReader(string connectionString, CommandType cmdType, string cmdText, Action<SqlDataReader> readerCallback, params SqlParameter[] commandParameters)
{
using (SqlCommand cmd = new SqlCommand())
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
// we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
cmd.Parameters.Clear();
readerCallback.Invoke(rdr);
}
}
catch (SqlException ex)
{
throw ex;
}
}
}
}
/// <summary>
/// ExecuteScalar
/// </summary>
/// <param name="connectionString">连接数据库字符串</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="commandParameters">Command Parameters</param>
/// <returns>return object</returns>
public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
using (SqlCommand cmd = new SqlCommand())
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
}
/// <summary>
/// ExecuteScalar
/// </summary>
/// <param name="connection">SqlConnection object</param>
/// <param name="cmdType">Command Type</param>
/// <param name="cmdText">Command Text</param>
/// <param name="commandParameters">Command Parameters</param>
/// <returns>return object</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{

using (SqlCommand cmd = new SqlCommand())
{
PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}

/// <summary>
/// Bulk insert data to db
/// </summary>
/// <param name="connectionString">db connection string</param>
/// <param name="tableName">table name</param>
/// <param name="dt">datatable</param>
/// <param name="columnNames">column name array</param>
/// <returns></returns>
public static void BulkInsert(string connectionString, string tableName, DataTable dt, string[] columnNames)
{
var sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
//sbc.NotifyAfter = 10000;
sbc.BulkCopyTimeout = 5000;
//sbc.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnRowsCopied);
sbc.NotifyAfter = dt.Rows.Count;
sbc.DestinationTableName = tableName;

foreach (var column in columnNames)
{
sbc.ColumnMappings.Add(column, column);
}

sbc.WriteToServer(dt);
sbc.Close();
sbc = null;
}

/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
/// <param name="cmdText">Command text, e.g. Select * from Products</param>
/// <param name="cmdParms">SqlParameters to use in the command</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{

if (conn.State != ConnectionState.Open)
conn.Open();

cmd.Connection = conn;
cmd.CommandText = cmdText;

if (trans != null)
cmd.Transaction = trans;

cmd.CommandType = cmdType;
cmd.CommandTimeout = 3600;

if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name="cmd">SqlCommand object</param>
/// <param name="conn">SqlConnection object</param>
/// <param name="trans">SqlTransaction object</param>
/// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType)
{

if (conn.State != ConnectionState.Open)
conn.Open();

cmd.Connection = conn;

if (trans != null)
cmd.Transaction = trans;

cmd.CommandType = cmdType;

}
}
}

你可能感兴趣的:(Excel)