namespace VS
{
public class InOutExcel
{
//把当前查询结果导出Excel
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="dtExcel">数据源</param>
public static void SaveAsExcel(System.Data.DataTable dtExcel)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != 0)
{
//导出到execl
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
excel.Application.Workbooks.Add(true);
excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
if (excel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
sheet.Name = "test";
int m = 0, n = 0;
//生成列名称 这里i是从1开始的 因为我第0列是个隐藏列ID 没必要写进去
for (int i = 0; i < dtExcel.Columns.Count; i++)
{
excel.Cells[1, i + 1] = dtExcel.Columns[i].Caption.ToString();
}
//填充数据
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
//j也是从1开始 原因如上 每个人需求不一样
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
if (dtExcel.Rows[i][j].ToString().GetType() == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dtExcel.Rows[i][j].ToString().Trim();
}
else
{
excel.Cells[i + 2, j + 1] = dtExcel.Rows[i][j].ToString().Trim();
}
}
}
sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
book.Close(false, miss, miss);
books.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//toolStripProgressBar1.Value = 0;
System.Diagnostics.Process.Start(strName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误提示");
}
finally
{
//excel.Quit();
KillSpecialExcel(excel);
}
}
}
回复 更多评论