怎样实现C#保存Excel功能 有朋友说用myExcel可以实现,但是,具体怎么实现啊,有没有哪位朋友可以说说,或者给我些资料,网站之类的 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 你在网上搜一下 c#操作EXCEL答案有很多。如果搜不到再来问,一定给你解答。 gridview导出Excel: public static void Export(DataGridView dataGridView) { if (dataGridView != null) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = "Sheet1.xls"; saveFileDialog.DefaultExt = ".xls"; saveFileDialog.FileOk += new CancelEventHandler(delegate(object sender, CancelEventArgs e) { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); _Workbook xWb = excel.Workbooks.Add(true); _Worksheet xWs = (_Worksheet)xWb.ActiveSheet; try { List<string> listDisplayCol = new List<string>(); List<string> listHeaderText = new List<string>(); foreach (DataGridViewColumn col in dataGridView.Columns) { if (col.Displayed) { listDisplayCol.Add(col.Name); listHeaderText.Add(col.HeaderText); } } Range rowRange = xWs.get_Range(excel.Cells[1, 1], excel.Cells[1, listHeaderText.Count]); rowRange.Value2 = listHeaderText.ToArray(); ArrayList arrayList = new ArrayList(listDisplayCol.Count); for (int i = 0; i < dataGridView.Rows.Count; i++) { DataGridViewRow eachRow = dataGridView.Rows[i]; arrayList.Clear(); foreach (string colName in listDisplayCol) { if (eachRow.Cells[colName] != null && eachRow.Cells[colName].Value != null) { arrayList.Add(eachRow.Cells[colName].Value.ToString()); } else { arrayList.Add(""); } } rowRange = xWs.get_Range(excel.Cells[i + 2, 1], excel.Cells[i + 2, listDisplayCol.Count]); rowRange.Value2 = arrayList.ToArray(); } xWs.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); xWb.Saved = true; excel.DisplayAlerts = false; } catch (Exception ex) { xWb.Saved = true; MessageBox.Show("保存失败!错误原因:" + ex.Message); } finally { excel.Quit(); excel = null; GC.Collect(); } }); saveFileDialog.ShowDialog(); } } 需要在项目里引入Microsoft.Office.Interop.Excel.dll文件. 这个是Datatable 导出到excel.你可以借鉴下别人写的。protected void btnDao_Click(object sender, EventArgs e) { if (txtstart.Value=="" && txtend.Value=="") { GridView1.DataBind(); } else { DataTable dt = SqlHelper.SqlDataAdapter("select [phone],[slno],[sltime],[uname],[address],[gh],[btype],[jibie],[yfzg],[jtxinxi],[jtname],[tsgr],[tsfg],[zfyyuan],[mtjz],[zyh],[zdqy],[xzq],[wqywz],[qylx],[xhfg],[thzl],[kstime],[tsxianxiang],[nrbc],[jsnr],[jieshi],[tijiao] from results where sltime between '" + txtstart.Value + "' and '" + txtend.Value + "'"); int[] index ={ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 }; string[] haeads ={ "受理号码", "流水号", "受理时间", "用户姓名", "地区", "工号", "品牌类型", "用户级别", "预付费中高端", "集团信息", "集团名称", "特殊个人信息", "特殊覆盖", "政府要员补充", "媒体记者", "专业户", "重点区域类型", "行政区", "微区域位置", "区域类型", "信号覆盖情况", "通话质量类型", "开始时间", "投诉现象", "内容补充", "解释内容", "是否接受解释", "是否需提交单" }; string name = Server.MapPath("file/template.xls"); ExportToExcel(dt, Server.MapPath("file/template.xls"), index, haeads); System.IO.FileInfo aFile = new System.IO.FileInfo(name); string na = Path.GetFileName(name); Response.Clear(); Response.ClearHeaders(); Response.BufferOutput = false; Response.ContentType = "application/ms-excel"; //Response.AddHeader("Content-Disposition","attachment;filename="+na); //上面这条中文会乱码,应该下面这样写 Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(na, System.Text.Encoding.UTF8)); Response.AddHeader("Content-Length", aFile.Length.ToString()); Response.WriteFile(name); Response.Flush(); Response.End(); } } //导出方法 public static bool ExportToExcel(System.Data.DataTable table, string excelName, int[] columnIndexs, string[] columnHeads) { #region 将方法中用到的所有Excel变量声明在方法最开始,以便最后统一回收。 object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.ApplicationClass oExcel = new Microsoft.Office.Interop.Excel.ApplicationClass(); Microsoft.Office.Interop.Excel.Workbook obook = null; Microsoft.Office.Interop.Excel.Worksheet oSheet = null; Microsoft.Office.Interop.Excel.Range range = null; #endregion try { obook = oExcel.Workbooks.Add(""); oSheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets[1]; int rCount, cCount; rCount = table.Rows.Count; cCount = table.Columns.Count; object obj = System.Reflection.Missing.Value; if (cCount < columnIndexs.Length || cCount < columnHeads.Length) { throw new ArgumentOutOfRangeException("columnIndexs 与 columnHeads 长度必须一致。"); } for (int i = 1; i <= columnIndexs.Length; i++) { //Excel.Range = (Excel.Range)oSheet.Columns.get_Item(i, obj); range = (Microsoft.Office.Interop.Excel.Range)oSheet.Columns.get_Item(i, obj); range.NumberFormatLocal = "@"; } for (int c = 0; c < columnIndexs.Length; c++) { oSheet.Cells[1, c + 1] = columnHeads[c]; for (int r = 1; r <= rCount; r++) { oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString(); } } obook.Saved = true; obook.SaveCopyAs(excelName); //必须调用 obook.Close(), 否则无法释放进程。 obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value); return true; } catch (Exception ex) { throw ex; } finally { // 调用System.Runtime.InteropServices.Marshal.ReleaseComObject(object)方法释放方法中 //用到的所有的Excel 变量, 记住是所有的。 比如说此方法中的range 对象, 就容易被遗忘。 System.Runtime.InteropServices.Marshal.ReleaseComObject(range); System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(obook); // 很多文章上都说必须调用此方法, 但是我试过没有调用oExcel.Quit() 的情况, 进程也能安全退出, //还是保留着吧。 oExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel); // 垃圾回收是必须的。 测试如果不执行垃圾回收, 无法关闭Excel 进程。 GC.Collect(); } } googleearth 二次开发求助 为什么老是提示SqlBulkCopy 来自数据源的 String 类型的给定值不能转换为指定目标列的类型int C# 打印自定义纸张,预览和实际打印有差距! Lucene3.0.2创建索引的问题 C语言用什么软件编程 C#中哪个类可以返回字段名称呢? 我的一个很简单的程序调试问题 高手帮忙,这句代码的意思 怎么把json格式的字符串写入指定的json文件中 怎么过滤数据集表中的记录? 我想用 C# 写一个简单测试 执行速度的程式 在MVC里如何获得页面上的控件名称?
如果搜不到再来问,一定给你解答。
{
if (dataGridView != null)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "Sheet1.xls";
saveFileDialog.DefaultExt = ".xls";
saveFileDialog.FileOk += new CancelEventHandler(delegate(object sender, CancelEventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
_Workbook xWb = excel.Workbooks.Add(true);
_Worksheet xWs = (_Worksheet)xWb.ActiveSheet;
try
{
List<string> listDisplayCol = new List<string>();
List<string> listHeaderText = new List<string>();
foreach (DataGridViewColumn col in dataGridView.Columns)
{
if (col.Displayed)
{
listDisplayCol.Add(col.Name);
listHeaderText.Add(col.HeaderText);
}
}
Range rowRange = xWs.get_Range(excel.Cells[1, 1], excel.Cells[1, listHeaderText.Count]);
rowRange.Value2 = listHeaderText.ToArray();
ArrayList arrayList = new ArrayList(listDisplayCol.Count);
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
DataGridViewRow eachRow = dataGridView.Rows[i];
arrayList.Clear();
foreach (string colName in listDisplayCol)
{
if (eachRow.Cells[colName] != null && eachRow.Cells[colName].Value != null)
{
arrayList.Add(eachRow.Cells[colName].Value.ToString());
}
else
{
arrayList.Add("");
}
}
rowRange = xWs.get_Range(excel.Cells[i + 2, 1], excel.Cells[i + 2, listDisplayCol.Count]);
rowRange.Value2 = arrayList.ToArray();
} xWs.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xWb.Saved = true;
excel.DisplayAlerts = false;
}
catch (Exception ex)
{
xWb.Saved = true;
MessageBox.Show("保存失败!错误原因:" + ex.Message);
}
finally
{
excel.Quit();
excel = null;
GC.Collect();
}
});
saveFileDialog.ShowDialog();
}
}
{
if (txtstart.Value=="" && txtend.Value=="")
{
GridView1.DataBind();
}
else
{
DataTable dt = SqlHelper.SqlDataAdapter("select [phone],[slno],[sltime],[uname],[address],[gh],[btype],[jibie],[yfzg],[jtxinxi],[jtname],[tsgr],[tsfg],[zfyyuan],[mtjz],[zyh],[zdqy],[xzq],[wqywz],[qylx],[xhfg],[thzl],[kstime],[tsxianxiang],[nrbc],[jsnr],[jieshi],[tijiao] from results where sltime between '" + txtstart.Value + "' and '" + txtend.Value + "'");
int[] index ={ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 };
string[] haeads ={ "受理号码", "流水号", "受理时间", "用户姓名", "地区", "工号", "品牌类型", "用户级别", "预付费中高端", "集团信息", "集团名称", "特殊个人信息", "特殊覆盖", "政府要员补充", "媒体记者", "专业户", "重点区域类型", "行政区", "微区域位置", "区域类型", "信号覆盖情况", "通话质量类型", "开始时间", "投诉现象", "内容补充", "解释内容", "是否接受解释", "是否需提交单" };
string name = Server.MapPath("file/template.xls");
ExportToExcel(dt, Server.MapPath("file/template.xls"), index, haeads);
System.IO.FileInfo aFile = new System.IO.FileInfo(name);
string na = Path.GetFileName(name);
Response.Clear();
Response.ClearHeaders();
Response.BufferOutput = false;
Response.ContentType = "application/ms-excel";
//Response.AddHeader("Content-Disposition","attachment;filename="+na);
//上面这条中文会乱码,应该下面这样写
Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(na, System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", aFile.Length.ToString());
Response.WriteFile(name);
Response.Flush();
Response.End();
}
}
//导出方法
public static bool ExportToExcel(System.Data.DataTable table, string excelName, int[] columnIndexs, string[] columnHeads)
{
#region 将方法中用到的所有Excel变量声明在方法最开始,以便最后统一回收。
object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.ApplicationClass oExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook obook = null;
Microsoft.Office.Interop.Excel.Worksheet oSheet = null;
Microsoft.Office.Interop.Excel.Range range = null;
#endregion
try
{
obook = oExcel.Workbooks.Add("");
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Worksheets[1];
int rCount, cCount;
rCount = table.Rows.Count;
cCount = table.Columns.Count;
object obj = System.Reflection.Missing.Value; if (cCount < columnIndexs.Length || cCount < columnHeads.Length)
{
throw new ArgumentOutOfRangeException("columnIndexs 与 columnHeads 长度必须一致。");
}
for (int i = 1; i <= columnIndexs.Length; i++)
{
//Excel.Range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
range = (Microsoft.Office.Interop.Excel.Range)oSheet.Columns.get_Item(i, obj);
range.NumberFormatLocal = "@";
}
for (int c = 0; c < columnIndexs.Length; c++)
{
oSheet.Cells[1, c + 1] = columnHeads[c];
for (int r = 1; r <= rCount; r++)
{
oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString();
}
}
obook.Saved = true;
obook.SaveCopyAs(excelName); //必须调用 obook.Close(), 否则无法释放进程。
obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
// 调用System.Runtime.InteropServices.Marshal.ReleaseComObject(object)方法释放方法中
//用到的所有的Excel 变量, 记住是所有的。 比如说此方法中的range 对象, 就容易被遗忘。 System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(obook); // 很多文章上都说必须调用此方法, 但是我试过没有调用oExcel.Quit() 的情况, 进程也能安全退出,
//还是保留着吧。
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
// 垃圾回收是必须的。 测试如果不执行垃圾回收, 无法关闭Excel 进程。
GC.Collect();
}
}