using System;
using System.Data;
using System.Windows.Forms;
using System.Data;
using System.Windows.Forms;
// 添加引用->Com->Microsoft Excel 12.0 Ojbect Library
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Code", typeof(string));
dt.Columns.Add("Name", typeof(string));
{
DataTable dt = new DataTable();
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Code", typeof(string));
dt.Columns.Add("Name", typeof(string));
DataRow row = null;
while (dt.Rows.Count < 3)
{
row = dt.NewRow();
row[0] = "A";
row[1] = "B";
row[2] = 'C';
dt.Rows.Add(row);
}
while (dt.Rows.Count < 3)
{
row = dt.NewRow();
row[0] = "A";
row[1] = "B";
row[2] = 'C';
dt.Rows.Add(row);
}
try
{
ExportDataTable(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
{
ExportDataTable(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ExportDataTable(DataTable table)
{
Excel.Application excel = new Excel.Application();
{
Excel.Application excel = new Excel.Application();
Excel.Workbook book = excel.Workbooks.Add(Missing.Value);
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
for (int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[1, col + 1] = table.Columns[col].ColumnName;
}
{
sheet.Cells[1, col + 1] = table.Columns[col].ColumnName;
}
Excel.Range range = excel.get_Range(excel.Cells[1, 1], excel.Cells[1, table.Columns.Count]);
range.Interior.ColorIndex = 42;
range.Interior.ColorIndex = 42;
for (int row = 0; row < table.Rows.Count; row++)
{
for (int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[row + 2, col + 1] = table.Rows[row][col].ToString();
}
}
{
for (int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[row + 2, col + 1] = table.Rows[row][col].ToString();
}
}
// 准备把工作溥保存到哪个位置 (保存为一个.xls文件)
book.Close(true, @"C:/Documents and Settings/ch/Desktop/新产品上传模板(办事处).xls", Missing.Value);
excel.Quit();
GC.Collect();
}
}
}
excel.Quit();
GC.Collect();
}
}
}