using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Windows.Forms;
namespace PAL_MES.BRLibrary
{
class CDealExcel
{
public void ExportToExcel(DataTable dt)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Application.Workbooks.Add(true);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.ActiveSheet;
xlSheet.Name = "Result";
Excel.Range ra;
xlApp.Visible = true;
xlApp.UserControl = false;
xlApp.DisplayAlerts = false;
int iRow = dt.Rows.Count;
int iCol = dt.Columns.Count;
string[,] x = new string[iRow, 1];
int i = 1;
foreach (DataColumn dc in dt.Columns)
{
xlSheet.Cells[1, i] = dt.Columns[i - 1].Caption.ToString();
int j = 0;
foreach (DataRow dr in dt.Rows)
{
x[j, 0] = dr[i - 1].ToString();
j = j + 1;
}
ra = xlSheet.get_Range(xlSheet.Cells[2, i], xlSheet.Cells[iRow + 1, i]);
ra.Value2 = x;
ra.EntireColumn.AutoFit();
i = i + 1;
}
ra = xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[dt.Rows.Count + 1, dt.Columns.Count]);
ra.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
ra.Font.Name = "Arial";
ra.Font.Size = 10;
ra = xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[1, dt.Columns.Count]);
ra.Interior.ColorIndex = 45;
ra.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
xlSheet = null;
xlBook = null;
xlApp = null;
GC.Collect();
}
public DataTable GetSheetFromExcel(string FileName)
{
Missing Miss = Missing.Value;
DataTable dtSheet = new DataTable();
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Open(FileName, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss, Miss);
dtSheet.Columns.Add("SheetName");
for (int i = 1; i <= xlBook.Sheets.Count; i++)
{
dtSheet.Rows.Add(((Excel.Worksheet)xlBook.Worksheets[i]).Name.ToString());
}
xlApp.Quit();
xlBook = null;
xlApp = null;
return dtSheet;
}
}
}
调用语句:CExcel.ExportToExcel(dt); CExcel 类名。