跪求导出带有模版的Excel例子

kangxin147 2012-03-28 04:41:27
我要做一个导出Excel的的功能,Excel模版中有标题有数据和总计项,期待哪为高手给个例子!网上找了很多,看不懂,例子都不完整!
...全文
276 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
GlyphVectory 2012-04-01
  • 打赏
  • 举报
回复
去我那里资源下载吧,有例子。代码。你只要转入datatable就行了。
kangxin147 2012-03-29
  • 打赏
  • 举报
回复
插入数据时,能够从第三行开始并且插入的数据不会覆盖Excel表的最下边一行就好!
kangxin147 2012-03-29
  • 打赏
  • 举报
回复
我不是要往固定的单元格填写东西!是往表格的中间填充内容,表格上边有一大标题,标题下面是列名,中间是内容,内容下边显示合计和一些固定的内容!
ijwsoft 2012-03-29
  • 打赏
  • 举报
回复
http://blog.csdn.net/keenweiwei/article/details/7278613
Ryan20082009 2012-03-29
  • 打赏
  • 举报
回复
我给你一个很完整的导出例子,记得给分,这是我项目中做的,直接给你复制了。。。
1、执行导出按钮
//导出客户信息。
protected void but_ExcelImport_Click(object sender, EventArgs e)
{
HQSoft.HQBLL.TB_Customer tbBll = new HQBLL.TB_Customer();
Aspose.Cells.Workbook workBook = new Aspose.Cells.Workbook();
Aspose.Cells.Worksheet sheet = workBook.Worksheets[0];
DataTable dt = tbBll.GetList("").Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
sheet.Cells[0, 0].PutValue("客户编号");
sheet.Cells[0, 1].PutValue("客户名称");
sheet.Cells[0, 2].PutValue("客户全称");
sheet.Cells[0, 3].PutValue("快捷录入");
sheet.Cells[0, 4].PutValue("客户类型");
sheet.Cells[0, 5].PutValue("业务人员");
sheet.Cells[0, 6].PutValue("客户主联系人");
sheet.Cells[0, 7].PutValue("客户主联系电话");
sheet.Cells[0, 8].PutValue("客户邮件");
sheet.Cells[0, 9].PutValue("客户地址");
sheet.Cells[0, 10].PutValue("客户传真");
sheet.Cells[0, 11].PutValue("结算周期");
sheet.Cells[0, 12].PutValue("结算方式");
DataRow dr = dt.Rows[i];
sheet.Cells[i + 1, 0].PutValue(dt.Rows[i][1]);
sheet.Cells[i + 1, 1].PutValue(dt.Rows[i][2]);
sheet.Cells[i + 1, 2].PutValue(dt.Rows[i][3]);
sheet.Cells[i + 1, 3].PutValue(dt.Rows[i][4]);
sheet.Cells[i + 1, 4].PutValue(dt.Rows[i][5]);
sheet.Cells[i + 1, 5].PutValue(dt.Rows[i][6]);
sheet.Cells[i + 1, 6].PutValue(dt.Rows[i][7]);

sheet.Cells[i + 1, 7].PutValue(dt.Rows[i][8]);
sheet.Cells[i + 1, 8].PutValue(dt.Rows[i][9]);
sheet.Cells[i + 1, 9].PutValue(dt.Rows[i][10]);
sheet.Cells[i + 1, 10].PutValue(dt.Rows[i][11]);
sheet.Cells[i + 1, 11].PutValue(dt.Rows[i][12]);
sheet.Cells[i + 1, 12].PutValue(dt.Rows[i][13]);
}
string fileName = "";
fileName = "Customer_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; // 文件名
workBook.Save(Server.MapPath("../Customer/tmpCustomer/" + fileName));
DownLoadFile(Server.MapPath("../Customer/tmpCustomer/"), fileName);
}
2、 //导出时候下载并上传临时文件。
private bool DownLoadFile(string _FilePath, string _FileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenRead(_FilePath + "\\" + _FileName);
byte[] FileData = new byte[fs.Length];
fs.Read(FileData, 0, (int)fs.Length);
Response.Clear();
Response.AddHeader("Content-Type", "application/ms-excel");
string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
Response.AddHeader("Content-Length", fs.Length.ToString());
Response.BinaryWrite(FileData);
fs.Close();
//删除服务器临时文件
//System.IO.File.Delete(_FilePath + "\\" + _FileName);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
ex.Message.ToString();
return false;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
3、 //Excel导入DtataSet操作。
public DataSet ExecleToDataSet(string filenameurl, string table)
{
DataSet ds = new DataSet();
try
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
odda.Fill(ds, table);
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('Excel文件数据有误!');</script>");

}
return ds;
}
Mlovecoding 2012-03-28
  • 打赏
  • 举报
回复

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using MySchool.Models;
using System.Data.OleDb;
using System.Data;

namespace MySchool.Excel
{
public class ExcelHandle
{
#region 将员工信息导入Excel中并设置Excel基本样式
/// <summary>
/// 将员工信息导入Excel中并设置Excel基本样式
/// </summary>
public void GetResultDataToExcel(DataGridView dgvResult)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);

excel.Caption = "XXXX";

//设置Excel列名
excel.Cells[1, 1] = "姓名";
excel.Cells[1, 2] = "名称";
excel.Cells[1, 3] = "result";
excel.Cells[1, 4] = "时间";

excel.get_Range(excel.Cells[1, 1], excel.Cells[1, 4]).Font.Bold = true;
excel.get_Range(excel.Cells[1, 1], excel.Cells[1, 4]).Font.ColorIndex = 0;
excel.get_Range(excel.Cells[1, 1], excel.Cells[1, 4]).Borders.LineStyle = XlLineStyle.xlContinuous;
for (int m = 0; m < dgvResult.Rows.Count; m++)
{
DataGridViewComboBoxCell dgvCbo = (DataGridViewComboBoxCell)dgvResult.Rows[m].Cells["StudentNo"];
excel.Cells[m + 2, 1] = dgvCbo.FormattedValue.ToString();
}
int i;
for (i = 0; i < dgvResult.Rows.Count; i++)
{
excel.Cells[i + 2, 2] = dgvResult.Rows[i].Cells["SubjectName"].Value.ToString();
excel.Cells[i + 2, 3] = dgvResult.Rows[i].Cells["Result"].Value.ToString();
excel.Cells[i + 2, 4] = dgvResult.Rows[i].Cells["Date"].Value.ToString();
}
excel.get_Range(excel.Cells[1, 1], excel.Cells[i + 2, 4]).HorizontalAlignment = XlHAlign.xlHAlignLeft;
excel.Visible = true;
}



#endregion
/// <summary>
/// 将员工信息导入Excel中并设置Excel基本样式
/// </summary>
public void GetStudentInfoDataToExcel(DataGridView dgvStuInfor,int ype)
{
Microsoft.Office.Interop.Excel.Application excel =
new Microsoft.Office.Interop.Excel.Application();
excel.SheetsInNewWorkbook = 1;
excel.Workbooks.Add();

//设置Excel列名
excel.Cells[1, 1] = "工号";
excel.Cells[1, 2] = "密码";
excel.Cells[1, 3] = "姓名";
excel.Cells[1, 4] = "性别";
excel.Cells[1, 5] = "学历";
excel.Cells[1, 6] = "电话";
excel.Cells[1, 7] = "地址";
excel.Cells[1, 8] = "出生年月日";
excel.Cells[1, 9] = "邮箱";
excel.Cells[1, 10] = "身份证号";

Range range = excel.get_Range(excel.Cells[1, 1], excel.Cells[1, 10]);
range.Font.Bold = true;
range.Font.ColorIndex = 0;
range.Interior.ColorIndex = 15;
range.Borders.LineStyle = XlLineStyle.xlContinuous;

int i = 0, j = 0;
for (i = 0; i < dgvStuInfor.Rows.Count; i++)
{
for (j = 0; j < 3; j++)
{
excel.Cells[i + 2, j + 1] = dgvStuInfor.Rows[i].Cells[j].Value.ToString();
}
excel.Cells[i + 2, 4] =
dgvStuInfor.Rows[i].Cells["Gender"].Value.ToString() == "False" ? "男" : "女";

DataGridViewComboBoxCell dgvCbo =
(DataGridViewComboBoxCell)dgvStuInfor.Rows[i].Cells["GradeId"];
excel.Cells[i + 2, 5] = dgvCbo.FormattedValue.ToString();

for (j = 5; j < 10; j++)
{
excel.Cells[i + 2, j + 1] = dgvStuInfor.Rows[i].Cells[j].Value.ToString();
}
}
excel.get_Range(excel.Cells[2, 8], excel.Cells[i + 2, 8]).NumberFormat = "yyyy-m-d";
//设置身份证号的格式
excel.get_Range(excel.Cells[2, 10], excel.Cells[i + 2, 10]).NumberFormatLocal = "0";
excel.get_Range(excel.Cells[1, 1], excel.Cells[i + 2, j + 2]).HorizontalAlignment
= XlHAlign.xlHAlignLeft;
//显示当前窗口
excel.Visible = true;
}

/// <summary>
/// 将员工信息导入Excel中-使用Excel 模板
/// </summary>
public void GetStudentInfoDataToExcel(DataGridView dgvStuInfor)
{
//创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
string fileName = Environment.CurrentDirectory + "/template/stuResult.xls";
excel.Application.Workbooks.Open(fileName);
int i = 0, j = 0;
for (i = 0; i < dgvStuInfor.Rows.Count; i++)
{
for (j = 0; j < 3; j++)
{
excel.Cells[i + 3, j + 1] = dgvStuInfor.Rows[i].Cells[j].Value.ToString();
}
excel.Cells[i + 3, 4] =
dgvStuInfor.Rows[i].Cells["Gender"].Value.ToString() == "False" ? "男" : "女";

DataGridViewComboBoxCell dgvCbo =
(DataGridViewComboBoxCell)dgvStuInfor.Rows[i].Cells["GradeId"];
excel.Cells[i + 3, 5] = dgvCbo.FormattedValue.ToString();

for (j = 5; j < 10; j++)
{
excel.Cells[i + 3, j + 1] = dgvStuInfor.Rows[i].Cells[j].Value.ToString();
}
}
string newFileName = Environment.CurrentDirectory + "/test.xls";
//保存当前活动的WorkBook
excel.ActiveWorkbook.SaveAs(newFileName, XlFileFormat.xlWorkbookNormal);
//关闭当前活动的WorkBook
excel.ActiveWorkbook.Close();
//退出Excel应用程序
excel.Quit();
}
#endregion

#region 从Excel中导入员工信息
/// <summary>
/// 从Excel中导出员工信息
/// </summary>
public System.Data.DataTable GetStudentInfoDataFromExcel(string filePath, string sheetName, bool useADONET)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";"
+ "Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
string strExcel = string.Format("select * from [{0}$] where [姓名] is not null", sheetName);
System.Data.DataTable dt = new System.Data.DataTable();

using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, conn);
adapter.Fill(dt);
}
foreach (DataRow dr in dt.Rows)
{
dr[2] = dr[2].ToString() == "男" ? "1" : "0";
}
return dt;
}

/// <summary>
/// 从Excel 导入数据到DataTable
/// </summary>
/// <param name="filePath">h带完整路径的Excel文件名</param>
/// <param name="sheetName">工作薄名字</param>
/// <returns>DataTable</returns>
public System.Data.DataTable GetStudentInfoDataFromExcel(string filePath, string sheetName)
{
System.Data.DataTable dt = new System.Data.DataTable();
//添加9个列
for (int i = 0; i < 9; i++)
{
dt.Columns.Add(new DataColumn());
}

Microsoft.Office.Interop.Excel.Application excel =
new Microsoft.Office.Interop.Excel.Application();
excel.Workbooks.Open(filePath);//打开Excel 文件

Worksheet sheet = null;
foreach (Worksheet wsheet in excel.ActiveWorkbook.Sheets)
{
if (wsheet.Name == sheetName)
{
sheet = wsheet;
break;
}
}
//读取单元格数据
if (sheet != null)
{
int row = 2;//当前行号
while (true)
{
//如果碰到姓名为空的行,则停止读取数据
Range rName = sheet.Cells[row, 2] as Range;
if (rName.Text.ToString().Trim().Length == 0)
{
break;
}

DataRow dr = dt.NewRow();
for (int i = 0; i < 9; i++)
{
//将行中的每列赋值
Range rContent = sheet.Cells[row, i + 1] as Range;
dr[i] = rContent.Text;
if (i == 2)//性别列处理为布尔值
{
dr[i] = dr[i].ToString() == "男" ? "1" : "0";
}
}
dt.Rows.Add(dr);
row += 1;
}
}
excel.ActiveWorkbook.Close();
excel.Quit();
return dt;
}

#endregion
}
}

bu在服务区 2012-03-28
  • 打赏
  • 举报
回复
原理就是往EXCEL固定的坐标写东西。。。。

原来搞过。。。这里没代码~~~
_萧萧 2012-03-28
  • 打赏
  • 举报
回复
我也是拿人家的过来
_萧萧 2012-03-28
  • 打赏
  • 举报
回复
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dtTemp"></param>
/// <param name="ServerPath"></param>
/// <param name="TextName"></param>
/// <param name="fc">将number格式化成string</param>
public static void ExportTasks(System.Data.DataTable dtTemp,string ServerPath,string TextName,int fc,string sName)
{
// 定义要使用的Excel 组件接口
// 定义Application 对象,此对象表示整个Excel 程序
Application excelApp = null;
// 定义Workbook对象,此对象代表工作薄
Workbook workBook;
// 定义Worksheet 对象,此对象表示Execel 中的一张工作表
Worksheet ws = null;
//定义Range对象,此对象代表单元格区域
Range range;

int dcell = 1;
int rowindex = 0; int colindex = 0;

int rowcount = dtTemp.Rows.Count;
int colcount = dtTemp.Columns.Count;
try
{
//初始化 Application 对象 excelApp
excelApp = new Application();
//在工作薄的第一个工作表上创建任务列表
workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
ws = (Worksheet)workBook.Worksheets[1];

// 命名工作表的名称为
ws.Name = !string.IsNullOrEmpty(sName) ? sName : "Sheet1" ;
//创建缓存
Object[,] objdata = new object[rowcount + 1, colcount];

//创建标题
foreach (System.Data.DataColumn dc in dtTemp.Columns)
{
objdata[rowindex, colindex++] = dc.ColumnName;
}
//获取数据
for (int i = 0; i < rowcount; i++)
{
dcell = 0;

for (int j = 0; j < colcount; j++)
{
objdata[i + 1, dcell++] = dtTemp.Rows[i][dtTemp.Columns[j].ColumnName].ToString();
}
}
//写入Excel
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount + 1, colcount]);
//range.NumberFormatLocal = "@";//所有字段格式化为文本格式
ws.get_Range(excelApp.Cells[2, fc], excelApp.Cells[rowcount + 1, fc]).NumberFormatLocal = "@";
range.Value2 = objdata;
System.Windows.Forms.Application.DoEvents();
//设置格式
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[1, colcount]);
range.Font.Bold = true;//标题粗体

excelApp.Cells.HorizontalAlignment = Constants.xlCenter; //全局左对齐
excelApp.Cells.EntireColumn.AutoFit();
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount + 1, colcount]);
range.Borders.LineStyle = 1;
//range.Font.Bold = true; //标题粗体
//显示 Excel
//excelApp.Visible = true;
workBook.SaveCopyAs(ServerPath.Replace("//", "\\") + TextName + ".xls");
workBook.Close(false, null, null);
excelApp.Quit();
ws = null;
}
catch (Exception ex)
{
WriteLog.SetErrorMsg("ExportTasks", "", ex.Message); //处理错误
excelApp.Quit();
throw ex;
}
}


/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dtTemp"></param>
public static void ExportCMB(System.Data.DataTable dtTemp, string ServerPath, string TextName)
{
// 定义要使用的Excel 组件接口
// 定义Application 对象,此对象表示整个Excel 程序
Application excelApp = null;
// 定义Workbook对象,此对象代表工作薄
Workbook workBook;
// 定义Worksheet 对象,此对象表示Execel 中的一张工作表
Worksheet ws = null;
//定义Range对象,此对象代表单元格区域
Range range;

int dcell = 1;
int colindex = 0;

int rowcount = dtTemp.Rows.Count;
int colcount = 14;
try
{
//初始化 Application 对象 excelApp
excelApp = new Application();
//在工作薄的第一个工作表上创建任务列表
workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
ws = (Worksheet)workBook.Worksheets[1];

// 命名工作表的名称为
ws.Name = "Sheet1";
//创建缓存
Object[,] objdata = new object[rowcount + 3, colcount];
objdata[0, 0] = "代发工资表";
objdata[1, 0] = "TF:QY1CWS1";
//创建标题
foreach (System.Data.DataColumn dc in dtTemp.Columns)
{
objdata[2, colindex++] = dc.ColumnName;
}
//获取数据
for (int i = 0; i < rowcount; i++)
{
dcell = 0;

for (int j = 0; j < colcount; j++)
{
objdata[i + 3, dcell++] = dtTemp.Rows[i][dtTemp.Columns[j].ColumnName].ToString();
}
}
//写入Excel
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount + 3, colcount]);
ws.get_Range(excelApp.Cells[4, 12], excelApp.Cells[rowcount + 3, 12]).NumberFormatLocal = "@";
//range.NumberFormatLocal = "@";
range.Value2 = objdata;
range.Font.Size = 10;
System.Windows.Forms.Application.DoEvents();
//设置格式
excelApp.Cells.HorizontalAlignment = Constants.xlLeft; //全局左对齐
excelApp.Cells.EntireColumn.AutoFit();
range = ws.get_Range(excelApp.Cells[3, 1], excelApp.Cells[rowcount + 3, colcount]);
//range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
range.Borders.LineStyle = 1;
//显示 Excel
//excelApp.Visible = true;
workBook.SaveCopyAs(ServerPath.Replace("//", "\\") + TextName + ".xls");
workBook.Close(false, null, null);
excelApp.Quit();
ws = null;

}
catch (Exception ex)
{
WriteLog.SetErrorMsg("ExportICBC", "", ex.Message); //处理错误
excelApp.Quit();
throw ex;
}
}
}
zhanglong_longlong 2012-03-28
  • 打赏
  • 举报
回复
www.51aspx.com

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧