日期:2014-05-18  浏览次数:20455 次

百分求VSTO动态导出EXCEL例子
百分求VSTO动态导出EXCEL例子

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Windows.Forms;

namespace Common
{
#region DataGrid数据导出到Excel
public class dg_to_Excel
{

public static void ToExcel(DataGridView dG_1, DataSet dS_1)
{
Excel.Application ExcelApp;
try
{
ExcelApp = new Excel.Application();
}
catch (Exception ex)
{
MessageBox.Show("无法启动Excel!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (ExcelApp == null)
{
MessageBox.Show("无法启动Excel!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
ExcelApp.Visible = true;

Excel.Workbooks WorkBooks = ExcelApp.Workbooks;
Excel._Workbook WorkBook = WorkBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Sheets WorkSheets = WorkBook.Sheets;
Excel._Worksheet WorkSheet = (Excel._Worksheet)WorkSheets.get_Item(1);
Excel.Range MyRange = null;
if (WorkSheet == null)
{
MessageBox.Show("无法添加ExcelSheets!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}

int i, j, l_ColCount, l_RowCount;
l_RowCount = dS_1.Tables[0].Rows.Count + 1;
l_ColCount = dG_1.ColumnCount;

object Cell1 = WorkSheet.Cells[1, 1], Cell2 = WorkSheet.Cells[l_RowCount, l_ColCount];
MyRange = WorkSheet.get_Range(Cell1, Cell1);

string[] ColumnsValues = new string[l_ColCount];
i = 1;
for (j = 1; j <= l_ColCount; j++)
{
if (dG_1.Columns[j-1].Width < 5) continue;
ColumnsValues[j - 1] = dG_1.Columns[j-1].HeaderText;
MyRange.set_Item(i, j, ColumnsValues[j - 1]);
}
for (i = 2; i <= l_RowCount; i++)
{
for (j = 1; j <= l_ColCount; j++)
{
if (dG_1.Columns[j - 1].Width < 5) continue;
ColumnsValues[j - 1] = dG_1[j - 1,i - 2].Value.ToString();
MyRange.set_Item(i, j, ColumnsValues[j - 1]);
}
}
// ExcelApp.Save("C:\\PowerReport\\Excel\\"+this.is_report_name+".xls");
// MessageBox.Show("导出数据到Excel成功!");
}
}
#endregion
}