|
|
|
Export DataSet, DataTable to Excel File using Excel Interop |
|
|
|
|
|
|
|
Code by พี่หมี
ExportExcel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using System.IO;
namespace TestExportExcel
{
class ExportExcel : IDisposable
{
private object missing = Type.Missing;
private object readOnly = true;
private Excel.Application xlApp;
private Excel.Workbook xlBook;
private Excel.Range xlRange;
private string filePath;
private string message;
private int sheetCount;
private int rowCount;
public ExportExcel(string FilePath)
{
filePath = FilePath;
message = "Hello World!!!";
sheetCount = 0;
rowCount = 0;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.ScreenUpdating = false;
xlApp.DisplayAlerts = false;
}
public bool Export(DataSet DsData)
{
if(!Create())
return false;
foreach (DataTable DtData in DsData.Tables)
{
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets.Add(missing, missing, missing, missing);
if(!FillData(xlSheet, DtData))
return false;
sheetCount++;
}
if(!Save())
return false;
message = string.Format("Export '{0}' Success. ({1} Sheets, {2} Rows)", Path.GetFileName(filePath), sheetCount.ToString("#,##0"), rowCount.ToString("#,##0"));
return true;
}
public bool Export(DataTable DtData)
{
if (!Create())
return false;
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets.Add(missing, missing, missing, missing);
if (!FillData(xlSheet, DtData))
return false;
sheetCount++;
if (!Save())
return false;
message = string.Format("Export '{0}' Success. ({1} Sheets, {2} Rows)", Path.GetFileName(filePath), sheetCount.ToString("#,##0"), rowCount.ToString("#,##0"));
return true;
}
public bool Export(DataSet DsData, string TableName)
{
return Export(DsData.Tables[TableName]);
}
public bool Export(DataSet DsData, int TableIndex)
{
return Export(DsData.Tables[TableIndex]);
}
protected bool Create()
{
bool result = false;
if (!File.Exists(filePath))
File.Delete(filePath);
try
{
xlBook = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
result = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
}
return result;
}
protected bool Save()
{
bool result = false;
try
{
xlBook.SaveAs(filePath, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
result = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
}
return result;
}
protected bool FillData(Excel.Worksheet xlSheet, DataTable DtData)
{
int row = 2;
int col = 1;
xlSheet.Name = DtData.TableName;
foreach (DataColumn Dc in DtData.Columns)
{
xlSheet.Cells[1, col] = string.Format("'{0}", Dc.ColumnName);
xlRange = (Excel.Range)xlSheet.Cells[1, col];
xlRange.Font.Name = "MS Sans Serif";
xlRange.Font.Size = 10;
xlRange.Interior.Color = System.Drawing.Color.LightYellow;
xlRange.Borders.Color = System.Drawing.Color.LightGray;
col++;
}
foreach (DataRow Dr in DtData.Rows)
{
col = 1;
foreach (DataColumn Dc in DtData.Columns)
{
xlRange = (Excel.Range)xlSheet.Cells[row, col];
xlRange.Font.Name = "MS Sans Serif";
xlRange.Font.Size = 10;
xlRange.Borders.Color = System.Drawing.Color.LightGray;
if (Dc.DataType == typeof(double) || Dc.DataType == typeof(float))
{
try
{
xlSheet.Cells[row, col] = Dr[col - 1];
xlRange.NumberFormat = "#,##0.00";
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
return false;
}
}
else if (Dc.DataType == typeof(int) || Dc.DataType == typeof(short) || Dc.DataType == typeof(ushort) ||
Dc.DataType == typeof(uint) || Dc.DataType == typeof(long) || Dc.DataType == typeof(ulong) ||
Dc.DataType == typeof(decimal))
{
try
{
xlSheet.Cells[row, col] = Dr[col - 1];
xlRange.NumberFormat = "#,##0";
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
return false;
}
}
else if (Dc.DataType == typeof(DateTime))
{
try
{
xlSheet.Cells[row, col] = Dr[col - 1];
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
return false;
}
}
else if (Dc.DataType == typeof(bool))
{
try
{
xlSheet.Cells[row, col] = Dr[col - 1];
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
return false;
}
}
else if (Dc.DataType == typeof(sbyte) || Dc.DataType == typeof(byte) || Dc.DataType == typeof(byte[]))
{
try
{
xlSheet.Cells[row, col] = null;
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
return false;
}
}
else
{
try
{
xlSheet.Cells[row, col] = string.Format("'{0}", Dr[col - 1]);
}
catch (System.Runtime.InteropServices.COMException ex)
{
message = ex.Message;
Dispose();
return false;
}
}
col++;
}
rowCount++;
row++;
}
return true;
}
public string Message
{
get { return message; }
}
public void Dispose()
{
if (xlApp != null)
{
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
GC.SuppressFinalize(xlRange);
GC.SuppressFinalize(xlBook);
GC.SuppressFinalize(xlApp);
GC.Collect();
xlRange = null;
xlBook = null;
xlApp = null;
}
}
}
}
วิธีใช้งาน
private void buttonExport_Click(object sender, EventArgs e)
{
saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Files|*.xlsx|Excel 97-2003 Files|*.xls|All Files|*.*";
saveFileDialog1.Title = "Export to Excel File";
saveFileDialog1.FileName = "test.xlsx";
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK && saveFileDialog1.FileName != string.Empty)
backgroundWorker1.RunWorkerAsync(saveFileDialog1.FileName);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
using (ExportExcel excel = new ExportExcel((string)e.Argument))
{
DataSet DsData = GetExportData();
bool result = excel.Export(DsData);
excel.Dispose();
if (!result)
{
MessageBox.Show(excel.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show(excel.Message, "Success", MessageBoxButtons.OK);
}
}
}
private DataSet GetExportData()
{
DataSet DsData = new DataSet();
.....
.....
.....
.....
.....
.....
.....
return DsData;
}
Tag : .NET, Excel (Excel.Application), Win (Windows App), C#, VS 2010 (.NET 4.x)
|
|
|
|
|
|
Date :
2012-06-22 11:24:49 |
By :
อิอิ |
View :
1956 |
Reply :
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
อยากได้ Export จาก VB2008 ไป Excel มั่งง่ะจ่ะ
|
|
|
|
|
Date :
2012-06-22 11:55:59 |
By :
Bill17259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 00
|