110,536
社区成员
发帖
与我相关
我的任务
分享
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using DMSClient.Lib;
using DMSClient.DMSCtrl;
//保存到Excel
public void SaveDataTableToExcel(System.Data.DataTable excelTable,string filePath)
{
Microsoft.Office.Interop.Excel.Application app =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
//让后台执行设置为不可见
app.Visible = false;
//新增加一个工作簿
Workbook wBook = app.Workbooks.Add(true);
//如果要打开已有的工作簿,则使用下面的注释语句
// Workbook wBook = app.Workbooks.Open(@"C:\YourPath\YourWorkbook.xls",
// missing, missing, missing, missing, missing, missing, missing,
// missing, missing, missing, missing, missing,missing, missing);
//取得一个工作表
//如果打开了已有的工作簿,也可以这样获取工作表Worksheet wSheet = wBook.ActiveSheet as Worksheet
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
if (excelTable.Rows.Count > 0)
{
int row = 0;
row = excelTable.Rows.Count;
int col = excelTable.Columns.Count;
allsize = row;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
string str = excelTable.Rows[i][j].ToString();
wSheet.Cells[i + 1, j + 1] = str;
}
}
}
int size = excelTable.Columns.Count;
for (int i = 0; i < size; i++)
{
wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
}
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
//保存工作簿
wBook.Save();
//保存excel文件
app.Save(filePath + "\\导出excel.xls");
}
catch(Exception err)
{
MessageBox.Show("导入Excel出错!错误原因:"+ err.Message, "错误提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
//确保Excel进程关闭
app.Quit();
app = null;
}
}
Excel.ApplicationClass excel = new Excel.ApplicationClass();
int rowIndex = 1;
int colIndex=0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table = 你的table,
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1,colIndex] = col.ColumnName;
}
foreach(DataRow row in table.Rows)
{
rowIndex++;
colIndex=0;
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
excel.Visible = false;
//excel.Visible = true;
excel.DisplayAlerts = false;
excel.ActiveWorkbook.SaveAs(strExcelFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Quit();
excel=null;
GC.Collect();//垃圾回收