大家帮帮忙啊!100分求用模板导出Excel之后如何能让用户选择保存路径,而不是用写死的路径,,在线等待!!!!!!!!!

michael_sw 2007-12-11 04:35:19
如果把导出的路径写死的话 可以导出来,但是不符合用户的需求啊!!
大家帮帮我 谢谢
代码::
public class ExcelHelper
{
protected string templetFile = null;
protected string outputFile = null;
protected object missing = Missing.Value;

/// <summary>
/// 构造函数,需指定模板文件和输出文件完整路径
/// </summary>
/// <param name="templetFilePath">Excel模板文件路径</param>
/// <param name="outputFilePath">输出Excel文件路径</param>
public ExcelHelper(string templetFilePath, string outputFilePath)
{
if (templetFilePath == null)
throw new Exception("Excel模板文件路径不能为空!");

if (outputFilePath == null)
throw new Exception("输出Excel文件路径不能为空!");

if (!File.Exists(templetFilePath))
throw new Exception("指定路径的Excel模板文件不存在!");

this.templetFile = templetFilePath;
this.outputFile = outputFilePath;

}

/// <summary>
/// 将DataTable数据写入Excel文件(套用模板并分页)
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="rows">每个WorkSheet写入多少行数据</param>
/// <param name="top">行索引</param>
/// <param name="left">列索引</param>
/// <param name="sheetPrefixName">WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2...”</param>
public void DataTableToExcel(DataTable dt, int top, int left, string sheetPrefixName)
{
int rowCount = dt.Rows.Count; //源DataTable行数
int colCount = dt.Columns.Count; //源DataTable列数
DateTime beforeTime;
DateTime afterTime;

if (sheetPrefixName == null || sheetPrefixName.Trim() == "")
sheetPrefixName = "Sheet";

//创建一个Application对象并使其可见
beforeTime = DateTime.Now;
Excel.Application app = new Excel.ApplicationClass();
app.Visible = true;
afterTime = DateTime.Now;

//打开模板文件,得到WorkBook对象
Excel.Workbook workBook = app.Workbooks._Open(templetFile, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing);

//得到WorkSheet对象
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);


#region 将源DataTable数据写入Excel
//获取要写入数据的WorkSheet对象,并重命名
Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);
sheet.Name = sheetPrefixName + "-" + 1;

//将dt中的数据写入WorkSheet
for (int j = 0; j < rowCount; j++)
{
for (int k = 0; k < colCount-1; k++)
{
sheet.Cells[top + j, left + k] = dt.Rows[j][k+1].ToString();
}
}

//NAR(sheet);

//写文本框数据
Excel.TextBox txtDate = (Excel.TextBox)sheet.TextBoxes("txtDate");
Excel.TextBox txtVersion = (Excel.TextBox)sheet.TextBoxes("txtVersion");

txtVersion.Text = DateTime.Now.ToString("yyyy");
txtDate.Text = DateTime.Now.ToString("MM");

#endregion

//输出Excel文件并退出
try
{
workBook._SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing); --outputFile就是写死的导出的路径!!!!!!!!!!!!!!!
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();

System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

workSheet = null;
workBook = null;
app = null;

GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception e)
{
throw e;
}
finally
{
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName("Excel");

//得不到Excel进程ID,暂时只能判断进程启动时间
//foreach (Process myProcess in myProcesses)
//{
// startTime = myProcess.StartTime;

// if (startTime > beforeTime && startTime < afterTime)
// {
// myProcess.Kill();
// }
//}
}

}
...全文
485 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq398465437 2012-08-07
  • 打赏
  • 举报
回复
求分享啊~
chuanyueniwo 2011-08-02
  • 打赏
  • 举报
回复
楼主怎么完成的,分享一下代码吧 ,谢谢啊 !!!!!!
michael_sw 2007-12-12
  • 打赏
  • 举报
回复
FancyBoy247 谢谢你的思路..这个办法可行,,
michael_sw 2007-12-12
  • 打赏
  • 举报
回复
完成了 谢谢
Eric_zdhz 2007-12-11
  • 打赏
  • 举报
回复
楼主,你的程序在服务器上运行的,让客户选择路径有何意义?
再说,也不可能让他选啊,那不是大大的后门?
michael_sw 2007-12-11
  • 打赏
  • 举报
回复
顶上去啊!!!!!!!!!各位大哥指教
michael_sw 2007-12-11
  • 打赏
  • 举报
回复
大哥 你说在我的方法中返回一个文件的存储路径,,,但是这个路径是用户设置的么???请指教..
FancyBoy247 2007-12-11
  • 打赏
  • 举报
回复
在你的文件保存的方法中反回一个文件存储的路径,然后写一个下载的方法,参数是一个文件的全路径.这样,就可以达到你要的效果了.
michael_sw 2007-12-11
  • 打赏
  • 举报
回复
strExcelFileName 这个路径是怎么传过来的


我的意思是 就像你下载东西的时候 它不是让你选择一个路径么 怎么才能把我这个代码改成那样的呢?>?
yang_147577 2007-12-11
  • 打赏
  • 举报
回复
试试这个
yang_147577 2007-12-11
  • 打赏
  • 举报
回复
protected System.Web.UI.WebControls.DataGrid dgShow;
protected System.Web.UI.WebControls.Button btnCom;
protected System.Web.UI.WebControls.Button btnMIME;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
BindData();


}
private DataSet BindData()
{
SqlConnection myConnection = new SqlConnection( "server=(local);uid=sa;pwd=111;database=Pubs" );
DataSet myDataSet = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter("Select * From Authors", myConnection );
myDataAdapter.Fill( myDataSet, "Authors" );
dgShow.DataSource = myDataSet.Tables[0].DefaultView;
dgShow.DataBind();
return myDataSet;

}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnMIME.Click += new System.EventHandler(this.btnMIME_Click);
this.btnCom.Click += new System.EventHandler(this.btnCom_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnMIME_Click(object sender, System.EventArgs e)
{
BindData();

Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename="
+ HttpUtility.UrlEncode("下载文件.xls",Encoding.UTF8 ) );


//如果输出为Word,修改为以下代码
//Response.ContentType = "application/ms-word"
//Response.AddHeader("Content-Disposition", "inline;filename=test.doc")
StringBuilder sb=new StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
sb.Append("<html><body>");
dgShow.RenderControl(hw);
sb.Append("</body></html>");
Response.Write(sb.ToString());
Response.End();
}

private void btnCom_Click(object sender, System.EventArgs e)
{
ExportToExcel(BindData(),Server.MapPath("ComExcel.xls"));

}
//从DataSet到出到Excel
#region 从DataSet到出到Excel
/// 导出指定的Excel文件
public void ExportToExcel(DataSet ds,string strExcelFileName)
{
if (ds.Tables.Count==0 || strExcelFileName=="") return;
doExport(ds,strExcelFileName);


}
/// 执行导出
private void doExport(DataSet ds,string strExcelFileName)
{

Excel.Application excel= new Excel.Application();
int rowIndex=1;
int colIndex=0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table=ds.Tables[0] ;
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.ActiveWorkbook.SaveAs(strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);
excel.Quit();
excel=null;
GC.Collect();//垃圾回收
}
#endregion
}
}
michael_sw 2007-12-11
  • 打赏
  • 举报
回复
崩溃了!!!!!来高手帮忙啊1!!!!!!!!!!!!!
michael_sw 2007-12-11
  • 打赏
  • 举报
回复
晕 没有高手知道么"????

62,046

社区成员

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

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

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

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