Excel文件操作的集合
1.一個讀取Excel文件並綁定到DataSet的方法.
2.將數據從DataSet倒入到Excel文件的方法.
1.一個讀取Excel文件並綁定到DataSet的方法.
private DataSet GetExcelDataIntoDataSet(string strExcelFilePath,string strSheetName)
{
FileInfo fileInfo = new FileInfo(strExcelFilePath);
if (!fileInfo.Exists)
return null;
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelFilePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(strConn);
DataSet dsExcel = new DataSet();
try
{
objConn.Open();
string strSql = "select * from [" + strSheetName + "$]";
System.Data.OleDb.OleDbDataAdapter odbcExcelDataAdapter = new System.Data.OleDb.OleDbDataAdapter(strSql, objConn);
odbcExcelDataAdapter.Fill(dsExcel,"ExcelData");
return dsExcel;
}
catch (Exception ex)
{
throw ex;
}
}
2.將數據從DataSet倒入到Excel文件的方法.
private void Test()
{
try
{
DataSet ds = GetDataSet();
ExportToExcelNoFormat(ds, strFile);
// 倒入操作結束,打開Excel文件操作
GC.Collect();
GC.WaitForPendingFinalizers();
Process p = new Process();
p.StartInfo.FileName = strFile;
p.Start();
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageType.E0001.CreateDialog(SecName).Show();
}
catch (Exception ex)
{
throw ex;
}
}
public static void ExportToExcelNoFormat(DataSet dataSet, string outputPath)
{
try
{
string strDir = new System.IO.FileInfo(outputPath).Directory.FullName;
if (!System.IO.Directory.Exists(strDir))
System.IO.Directory.CreateDirectory(strDir);
// Create the Excel Application object
ApplicationClass excelApp = new ApplicationClass();
// Create a new Excel Workbook
Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
int sheetIndex = 0;
List excelSheetList = new List();
Range myrange = null;
foreach (System.Data.DataTable dt in dataSet.Tables)
{
// Copy the DataTable to an object array
object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
// Copy the column names to the first row of the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
rawData[0, col] = dt.Columns[col].ColumnName;
}
// Copy the values to the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
}
}
// Calculate the final column letter
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (dt.Columns.Count > colCharsetLen)
{
finalColLetter = colCharset.Substring(
(dt.Columns.Count - 1) / colCharsetLen - 1, 1);
}
finalColLetter += colCharset.Substring(
(dt.Columns.Count - 1) % colCharsetLen, 1);
// Create a new Sheet
Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
excelWorkbook.Sheets.get_Item(++sheetIndex),
Type.Missing, 1, XlSheetType.xlWorksheet);
//Format Date type
int iCln = 0;
foreach (DataColumn dcln in dt.Columns)
{
iCln++;
if (dcln.DataType == typeof(DateTime))
{
myrange = excelSheet.get_Range(excelSheet.Cells[2, Convert.ToInt16(iCln)], excelSheet.Cells[dt.Rows.Count + 1, Convert.ToInt16(iCln)]);
myrange.NumberFormat = "yyyy-MM-dd";
}
}
excelSheetList.Add(excelSheet);
excelSheet.Name = dt.TableName;
// Fast data export to Excel
string excelRange = string.Format("A1:{0}{1}",
finalColLetter, dt.Rows.Count + 1);
excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
// Mark the first row as BOLD
((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
excelSheet.Columns.EntireColumn.AutoFit();
}
// Save and Close the Workbook
excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelWorkbook.Close(true, Type.Missing, Type.Missing);
// Release the Application object
excelApp.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheetList);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelWorkbook = null;
excelApp = null;
// Collect the unreferenced objects
//GC.Collect();
//GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
throw ex;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.