- 浏览: 64247 次
- 性别:
- 来自: 烟台
-
最新评论
Excel导入
一、在WEB中导入Excel的方法
方法1: 通过OleDB方式获取Excel文件的数据到DataSet中,然后将Dataset中的每笔记录插入到SQL Server
using System.Data.OleDb;
using System.Data.SqlClient;
第一步:首先上传到服务器
DataTable dt = new DataTable();
string strFileNewName = DateTime.Now.ToString(“yyyyMMddhhmmss”) + “.xls”;
FileUpload1.SaveAs(Server.MapPath(“Excel/Upload/” + strFileNewName));
第二步:将Excel的内容导入到DataTable中
using (OleDbConnection conn = new OleDbConnection(“Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =” + Server.MapPath(“Excel/Upload/” + strFileNewName) + “;Extended Properties=Excel 8.0″))
{
OleDbDataAdapter da = new OleDbDataAdapter(“select * from [sheet1$]“, conn);
da.Fill(dt);
}
第三步:将Datatable中的内容逐条插入到数据库中
using (SqlConnection SqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ToString()))
{
SqlConn.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
string workno = dt.Rows[i]["工号"].ToString();
string username = dt.Rows[i]["姓名"].ToString();
string sex = dt.Rows[i]["性别"].ToString();
SqlCommand cmd = new SqlCommand(“insert into employees(workno,empname,sex) values(‘” + workno + “‘,’” + username + “‘,’” + sex + “‘)”, conn);
cmd.ExecuteNonQuery();
}
}
Response.Write(“<script language=’javascript’>alert(‘文件上传成功!’);</script>”);
}
缺点:如果要插入的记录很多,打开关闭数据库的次数会是个天文数字。
二、在winform中导入Excel的方法
由于在windows中没有现成的upload控件可以使用,那么就自己造一个吧。
一个TextBox,一个Button,一个OpenFileDialog,你点Button,触发事件里把
if(OpenFileDialog.ShowDialog()==DialogResult.OK)
{
TextBox.Text = OpenFileDialog.FileName;
//之后想干吗就干吗
}
openFileDialog的Filter属性可以设置成 “Excel 文件|*.xls”;
Excel导出
在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件流输出写给浏览器。在Response输出时,t分隔的数据,导出Excel时,等价于分列,n等价于换行
1、将整个html全部输出Excel
此法将html中所有的内容,如按钮,表格,图片等全部输出到Excel中
Response.Clear();
Response.Buffer=true;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");
Response.ContentEncoding=System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
这里我们利用了ContentType属性,它默认的属性为text/html,这时将输出为超文本,即我们常见的网页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我们也可以输出(导出)图片、word文档等。下面的方法,也均用了这个属性。
注意:此方法确实可以导出excel,但更改ContentType的属性依然导出excel,我的测试环境是WPS Office 2010个人版,搜狗浏览器。
2、将GridView控件中的数据导出Excel (指定控件导出方式,这里我以GridView为例子,大家可以使用任意控件)
上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,GridView控件上的数据。
System.Web.UI.Control ctl=this.GridView1;
//DataGrid1是你在窗体中拖放的控件
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
如果你的DataGrid用了分页,它导出的是当前页的信息,也就是它导出的是DataGrid中显示的信息。而不是你select语句的全部信息。
注意:此法总是报错,提示gridview应该包含在runat标记内。
3、将DataSet中的数据导出Excel
有了上边的思路,就是将在导出的信息,输出(Response)客户端,这样就可以导出了。那么把DataSet中的数据导出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,这样就OK了。说明:参数ds应为填充有数据表的DataSet,文件名是全名,包括后缀名,如Excel2006.xls
public void CreateExcel(DataSet ds, string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName+".xls");
string colHeaders = "", ls_item = "";
//定义表对象与行对象,同时用DataSet对其值进行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
ls_item += row[i].ToString() + "\n";
}
else
{
ls_item += row[i].ToString() + "\t";
}
}
resp.Write(ls_item);
ls_item = "";
}
resp.End();
}
4、将dataview导出excel
若想实现更加富于变化或者行列不规则的excel导出时,可用本法
public void OutputExcel(DataView dv,string str)
{
//dv为要输出到Excel的数据,str为标题名称
GC.Collect();
Application excel;// = new Application();
int rowIndex=4;
int colIndex=1;
_Workbook xBk;
_Worksheet xSt;
excel= new ApplicationClass();
xBk = excel.Workbooks.Add(true);
xSt = (_Worksheet)xBk.ActiveSheet;
//
//取得标题
//
foreach(DataColumn col in dv.Table.Columns)
{
colIndex++;
excel.Cells[4,colIndex] = col.ColumnName;
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
}
//
//取得表格中的数据
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
if(col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
}
else
if(col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加载一个合计行
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = "合计";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//设置选中的部分的颜色
//
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
//
//取得整个报表的标题
//
excel.Cells[2,2] = str;
//
//设置整个报表的标题格式
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
//
//设置报表表格为最适应宽度
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
//
//设置整个报表的标题为跨列居中
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
//
//绘制边框
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗
//
//显示效果
//
excel.Visible=true;
//xSt.Export(Server.MapPath(".")+""+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(Server.MapPath(".")+""+this.xlfile.Text+".xls");
ds = null;
xBk.Close(false, null,null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
string path = Server.MapPath(this.xlfile.Text+".xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset="GB2312";
Response.ContentEncoding=System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(file.FullName);
// 停止页面的执行
Response.End();
}
二、winForm中导出Excel的方法:
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("自动编号,姓名,年龄");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.WriteFile(name); // 把文件流发送到客户端
Response.End();
public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[0];
sFile=url+"myExcel.xls";
sTemplate=url+"MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//定义一个新的工作簿
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item(1);
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item(1);
//命名该sheet
oSheet.Name="Sheet1";
oCells=oSheet.Cells;
//调用dumpdata过程,将数据导入到Excel中去
DumpData(dt,oCells);
//保存
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
//退出Excel,并且释放调用的COM资源
oExcel.Quit();
GC.Collect();
KillProcess("Excel");
}
private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有打开的进程
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}
2、方法2:
protected void ExportExcel()
{
gridbind();
if(ds1==null) return;
string saveFileName="";
// bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel文件|*.xls";
saveDialog.FileName ="Sheet1";
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")<0) return; //被点了取消
// excelapp.Workbooks.Open (App.path & 工程进度表.xls)
Excel.Application xlApp=new Excel.Application();
object missing=System.Reflection.Missing.Value;
if(xlApp==null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range;
string oldCaption=Title_label .Text.Trim ();
long totalCount=ds1.Tables[0].Rows.Count;
long rowRead=0;
float percent=0;
worksheet.Cells[1,1]=Title_label .Text.Trim ();
//写入字段
for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
{
worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName;
range=(Excel.Range)worksheet.Cells[2,i+1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//写入数值
Caption .Visible = true;
for(int r=0;r<ds1.Tables[0].Rows.Count;r++)
{
for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
{
worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
this.Caption.Text= "正在导出数据["+ percent.ToString("0.00") +"%]";
Application.DoEvents();
}
worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);
this.Caption.Visible= false;
this.Caption.Text= oldCaption;
range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
if(ds1.Tables[0].Columns.Count>1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
}
workbook.Close(missing,missing,missing);
xlApp.Quit();
}
3.从DataGridView里导出
/// <summary>
/// 常用方法,列之间加\t开。
/// </summary>
/// <remarks>
/// using System.IO;
/// </remarks>
/// <param name="dgv"></param>
private void DataGridViewToExcel(DataGridView dgv)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Execl files (*.xls)|*.xls";
dlg.CheckFileExists = false;
dlg.CheckPathExists = false;
dlg.FilterIndex = 0;
dlg.RestoreDirectory = true;
dlg.CreatePrompt = true;
dlg.Title = "保存为Excel文件";
if (dlg.ShowDialog() == DialogResult.OK)
{
Stream myStream;
myStream = dlg.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += "\t";
}
columnTitle += dgv.Columns[i].HeaderText;
}
sw.WriteLine(columnTitle);
//写入列内容
for (int j = 0; j < dgv.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dgv.Columns.Count; k++)
{
if (k > 0)
{
columnValue += "\t";
}
if (dgv.Rows[j].Cells[k].Value == null)
columnValue += "";
else
columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
}
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
}
4.把Excel数据读到DataSet里
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Execl files (*.xls)|*.xls";
dlg.CheckFileExists = false;
dlg.CheckPathExists = false;
dlg.FilterIndex = 0;
dlg.RestoreDirectory = true;
dlg.Title = "将Excel文件数据导入到DataSet";
dlg.ShowDialog();
DataSet ds = new DataSet();
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dlg.FileName.Trim() + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
using (OleDbConnection OleConn = new OleDbConnection(strConn))
{
OleConn.Open();
String sql = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
OleDaExcel.Fill(ds);
OleConn.Close();
}
三 字符串导出方法
1.一个通用的导出Excel的方法
/// <summary> /// 导出Execel /// </summary> /// <param name="columnTitle">列名以"\t分隔"如 列2\t列3\t列4</param> /// <param name="resutl">行,要与上面的列对应,列名以"\t分隔"如 列2\t列3\t列4 第行使用\n分隔 </param> private void ToExcel(string columnTitle, string resutl) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.Title = "保存为Excel文件"; if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); try { //写入列名称 sw.WriteLine(columnTitle); //写入行 sw.WriteLine(resutl); sw.Close(); myStream.Close(); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { sw.Close(); myStream.Close(); } } }
四、附注:
虽然都是实现导出excel的功能,但在asp.net和winform的程序中,实现的代码是各不相同的。在asp.net中,是在服务器端读取数据,在服务器端把数据以ms-excel的格式,以Response输出到浏览器(客户端);而在winform中,是把数据读到客户端(因为winform运行端就是客户端),然后调用客户端安装的office组件,将读到的数据写在excel
-------------------------------------------------------------------------
备注:可以将内存中的DataTable导出到Excel中,对分页的情况同样有效。
public void DataTable2Excel(DataTable dt)
{
//dt.Columns[0].ColumnName = "姓名"; //如果需要,可以将datatable中的英文标题改成中文
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称
HttpContext curContext = System.Web.HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.Default;
curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
curContext.Response.Charset = "";
curContext.Response.Write(BuildExportHTML(dt));//在Excel文件中写入数据
curContext.Response.Flush();
curContext.Response.End();
}
private static string BuildExportHTML(DataTable dt)
{
string result = string.Empty;
int readCnt = dt.Rows.Count;
int colCount = dt.Columns.Count;
int pagerecords = 5000;
string strTitleRow = "";
for (int j = 0; j < colCount; j++)
{
strTitleRow += dt.Columns[j].ColumnName + "\t";
}
strTitleRow += "\r\n";
StringBuilder strRows = new StringBuilder();
int cnt = 1;
for (int i = 0; i < readCnt; i++)
{
//strRows.Append("");
for (int j = 0; j < colCount; j++)
{
if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
{
if (dt.Rows[i][j].ToString() != string.Empty)
{
strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
}
else
strRows.Append("\t");
}
else
{
strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
}
}
strRows.Append("\r\n");
cnt++;
if (cnt >= pagerecords)
{
result += strRows.ToString();
strRows.Remove(0, strRows.Length);
cnt = 1;
}
}
result = strTitleRow + result + strRows.ToString();
return result;
}
以下代码只能导出当前页,如果分页的话,其他页无法导出,以后研究下怎样解决此问题。
this.UltraWebGridExcelExporter1.DownloadName = DateTime.Now.ToString("yyyyMMddhhmmss")+".xls";
Infragistics.Excel.Workbook workbook = new Infragistics.Excel.Workbook(); //创建新的Excel文件
workbook.Worksheets.Add("Sheet1"); //创建新的工作薄
this.UltraWebGridExcelExporter1.Export(this.UltraWebGrid1, workbook);//将表格显示数据导出到Excel文件中
文章来自: http://sufei.cnblogs.com/
一、在WEB中导入Excel的方法
方法1: 通过OleDB方式获取Excel文件的数据到DataSet中,然后将Dataset中的每笔记录插入到SQL Server
using System.Data.OleDb;
using System.Data.SqlClient;
第一步:首先上传到服务器
DataTable dt = new DataTable();
string strFileNewName = DateTime.Now.ToString(“yyyyMMddhhmmss”) + “.xls”;
FileUpload1.SaveAs(Server.MapPath(“Excel/Upload/” + strFileNewName));
第二步:将Excel的内容导入到DataTable中
using (OleDbConnection conn = new OleDbConnection(“Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =” + Server.MapPath(“Excel/Upload/” + strFileNewName) + “;Extended Properties=Excel 8.0″))
{
OleDbDataAdapter da = new OleDbDataAdapter(“select * from [sheet1$]“, conn);
da.Fill(dt);
}
第三步:将Datatable中的内容逐条插入到数据库中
using (SqlConnection SqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ToString()))
{
SqlConn.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
string workno = dt.Rows[i]["工号"].ToString();
string username = dt.Rows[i]["姓名"].ToString();
string sex = dt.Rows[i]["性别"].ToString();
SqlCommand cmd = new SqlCommand(“insert into employees(workno,empname,sex) values(‘” + workno + “‘,’” + username + “‘,’” + sex + “‘)”, conn);
cmd.ExecuteNonQuery();
}
}
Response.Write(“<script language=’javascript’>alert(‘文件上传成功!’);</script>”);
}
缺点:如果要插入的记录很多,打开关闭数据库的次数会是个天文数字。
二、在winform中导入Excel的方法
由于在windows中没有现成的upload控件可以使用,那么就自己造一个吧。
一个TextBox,一个Button,一个OpenFileDialog,你点Button,触发事件里把
if(OpenFileDialog.ShowDialog()==DialogResult.OK)
{
TextBox.Text = OpenFileDialog.FileName;
//之后想干吗就干吗
}
openFileDialog的Filter属性可以设置成 “Excel 文件|*.xls”;
Excel导出
在asp.net中导出Excel有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上;一种是将文件直接将文件流输出写给浏览器。在Response输出时,t分隔的数据,导出Excel时,等价于分列,n等价于换行
1、将整个html全部输出Excel
此法将html中所有的内容,如按钮,表格,图片等全部输出到Excel中
Response.Clear();
Response.Buffer=true;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");
Response.ContentEncoding=System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
这里我们利用了ContentType属性,它默认的属性为text/html,这时将输出为超文本,即我们常见的网页格式到客户端,如果改为ms-excel将将输出excel格式,也就是说以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。ContentType的属性还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我们也可以输出(导出)图片、word文档等。下面的方法,也均用了这个属性。
注意:此方法确实可以导出excel,但更改ContentType的属性依然导出excel,我的测试环境是WPS Office 2010个人版,搜狗浏览器。
2、将GridView控件中的数据导出Excel (指定控件导出方式,这里我以GridView为例子,大家可以使用任意控件)
上述方法虽然实现了导出的功能,但同时把按钮、分页框等html中的所有输出信息导了进去。而我们一般要导出的是数据,GridView控件上的数据。
System.Web.UI.Control ctl=this.GridView1;
//DataGrid1是你在窗体中拖放的控件
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
如果你的DataGrid用了分页,它导出的是当前页的信息,也就是它导出的是DataGrid中显示的信息。而不是你select语句的全部信息。
注意:此法总是报错,提示gridview应该包含在runat标记内。
3、将DataSet中的数据导出Excel
有了上边的思路,就是将在导出的信息,输出(Response)客户端,这样就可以导出了。那么把DataSet中的数据导出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,这样就OK了。说明:参数ds应为填充有数据表的DataSet,文件名是全名,包括后缀名,如Excel2006.xls
public void CreateExcel(DataSet ds, string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName+".xls");
string colHeaders = "", ls_item = "";
//定义表对象与行对象,同时用DataSet对其值进行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
ls_item += row[i].ToString() + "\n";
}
else
{
ls_item += row[i].ToString() + "\t";
}
}
resp.Write(ls_item);
ls_item = "";
}
resp.End();
}
4、将dataview导出excel
若想实现更加富于变化或者行列不规则的excel导出时,可用本法
public void OutputExcel(DataView dv,string str)
{
//dv为要输出到Excel的数据,str为标题名称
GC.Collect();
Application excel;// = new Application();
int rowIndex=4;
int colIndex=1;
_Workbook xBk;
_Worksheet xSt;
excel= new ApplicationClass();
xBk = excel.Workbooks.Add(true);
xSt = (_Worksheet)xBk.ActiveSheet;
//
//取得标题
//
foreach(DataColumn col in dv.Table.Columns)
{
colIndex++;
excel.Cells[4,colIndex] = col.ColumnName;
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
}
//
//取得表格中的数据
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
if(col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
}
else
if(col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加载一个合计行
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = "合计";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//设置选中的部分的颜色
//
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
//
//取得整个报表的标题
//
excel.Cells[2,2] = str;
//
//设置整个报表的标题格式
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
//
//设置报表表格为最适应宽度
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
//
//设置整个报表的标题为跨列居中
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
//
//绘制边框
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗
//
//显示效果
//
excel.Visible=true;
//xSt.Export(Server.MapPath(".")+""+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(Server.MapPath(".")+""+this.xlfile.Text+".xls");
ds = null;
xBk.Close(false, null,null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
string path = Server.MapPath(this.xlfile.Text+".xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset="GB2312";
Response.ContentEncoding=System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(file.FullName);
// 停止页面的执行
Response.End();
}
二、winForm中导出Excel的方法:
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("自动编号,姓名,年龄");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.WriteFile(name); // 把文件流发送到客户端
Response.End();
public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[0];
sFile=url+"myExcel.xls";
sTemplate=url+"MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//定义一个新的工作簿
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item(1);
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item(1);
//命名该sheet
oSheet.Name="Sheet1";
oCells=oSheet.Cells;
//调用dumpdata过程,将数据导入到Excel中去
DumpData(dt,oCells);
//保存
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
//退出Excel,并且释放调用的COM资源
oExcel.Quit();
GC.Collect();
KillProcess("Excel");
}
private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有打开的进程
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}
2、方法2:
protected void ExportExcel()
{
gridbind();
if(ds1==null) return;
string saveFileName="";
// bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel文件|*.xls";
saveDialog.FileName ="Sheet1";
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")<0) return; //被点了取消
// excelapp.Workbooks.Open (App.path & 工程进度表.xls)
Excel.Application xlApp=new Excel.Application();
object missing=System.Reflection.Missing.Value;
if(xlApp==null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range;
string oldCaption=Title_label .Text.Trim ();
long totalCount=ds1.Tables[0].Rows.Count;
long rowRead=0;
float percent=0;
worksheet.Cells[1,1]=Title_label .Text.Trim ();
//写入字段
for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
{
worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName;
range=(Excel.Range)worksheet.Cells[2,i+1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//写入数值
Caption .Visible = true;
for(int r=0;r<ds1.Tables[0].Rows.Count;r++)
{
for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
{
worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
this.Caption.Text= "正在导出数据["+ percent.ToString("0.00") +"%]";
Application.DoEvents();
}
worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);
this.Caption.Visible= false;
this.Caption.Text= oldCaption;
range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
if(ds1.Tables[0].Columns.Count>1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
}
workbook.Close(missing,missing,missing);
xlApp.Quit();
}
3.从DataGridView里导出
/// <summary>
/// 常用方法,列之间加\t开。
/// </summary>
/// <remarks>
/// using System.IO;
/// </remarks>
/// <param name="dgv"></param>
private void DataGridViewToExcel(DataGridView dgv)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Execl files (*.xls)|*.xls";
dlg.CheckFileExists = false;
dlg.CheckPathExists = false;
dlg.FilterIndex = 0;
dlg.RestoreDirectory = true;
dlg.CreatePrompt = true;
dlg.Title = "保存为Excel文件";
if (dlg.ShowDialog() == DialogResult.OK)
{
Stream myStream;
myStream = dlg.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += "\t";
}
columnTitle += dgv.Columns[i].HeaderText;
}
sw.WriteLine(columnTitle);
//写入列内容
for (int j = 0; j < dgv.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dgv.Columns.Count; k++)
{
if (k > 0)
{
columnValue += "\t";
}
if (dgv.Rows[j].Cells[k].Value == null)
columnValue += "";
else
columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
}
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
}
4.把Excel数据读到DataSet里
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Execl files (*.xls)|*.xls";
dlg.CheckFileExists = false;
dlg.CheckPathExists = false;
dlg.FilterIndex = 0;
dlg.RestoreDirectory = true;
dlg.Title = "将Excel文件数据导入到DataSet";
dlg.ShowDialog();
DataSet ds = new DataSet();
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dlg.FileName.Trim() + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
using (OleDbConnection OleConn = new OleDbConnection(strConn))
{
OleConn.Open();
String sql = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
OleDaExcel.Fill(ds);
OleConn.Close();
}
三 字符串导出方法
1.一个通用的导出Excel的方法
/// <summary> /// 导出Execel /// </summary> /// <param name="columnTitle">列名以"\t分隔"如 列2\t列3\t列4</param> /// <param name="resutl">行,要与上面的列对应,列名以"\t分隔"如 列2\t列3\t列4 第行使用\n分隔 </param> private void ToExcel(string columnTitle, string resutl) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.Title = "保存为Excel文件"; if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); try { //写入列名称 sw.WriteLine(columnTitle); //写入行 sw.WriteLine(resutl); sw.Close(); myStream.Close(); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { sw.Close(); myStream.Close(); } } }
四、附注:
虽然都是实现导出excel的功能,但在asp.net和winform的程序中,实现的代码是各不相同的。在asp.net中,是在服务器端读取数据,在服务器端把数据以ms-excel的格式,以Response输出到浏览器(客户端);而在winform中,是把数据读到客户端(因为winform运行端就是客户端),然后调用客户端安装的office组件,将读到的数据写在excel
-------------------------------------------------------------------------
备注:可以将内存中的DataTable导出到Excel中,对分页的情况同样有效。
public void DataTable2Excel(DataTable dt)
{
//dt.Columns[0].ColumnName = "姓名"; //如果需要,可以将datatable中的英文标题改成中文
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称
HttpContext curContext = System.Web.HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.Default;
curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
curContext.Response.Charset = "";
curContext.Response.Write(BuildExportHTML(dt));//在Excel文件中写入数据
curContext.Response.Flush();
curContext.Response.End();
}
private static string BuildExportHTML(DataTable dt)
{
string result = string.Empty;
int readCnt = dt.Rows.Count;
int colCount = dt.Columns.Count;
int pagerecords = 5000;
string strTitleRow = "";
for (int j = 0; j < colCount; j++)
{
strTitleRow += dt.Columns[j].ColumnName + "\t";
}
strTitleRow += "\r\n";
StringBuilder strRows = new StringBuilder();
int cnt = 1;
for (int i = 0; i < readCnt; i++)
{
//strRows.Append("");
for (int j = 0; j < colCount; j++)
{
if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
{
if (dt.Rows[i][j].ToString() != string.Empty)
{
strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
}
else
strRows.Append("\t");
}
else
{
strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
}
}
strRows.Append("\r\n");
cnt++;
if (cnt >= pagerecords)
{
result += strRows.ToString();
strRows.Remove(0, strRows.Length);
cnt = 1;
}
}
result = strTitleRow + result + strRows.ToString();
return result;
}
以下代码只能导出当前页,如果分页的话,其他页无法导出,以后研究下怎样解决此问题。
this.UltraWebGridExcelExporter1.DownloadName = DateTime.Now.ToString("yyyyMMddhhmmss")+".xls";
Infragistics.Excel.Workbook workbook = new Infragistics.Excel.Workbook(); //创建新的Excel文件
workbook.Worksheets.Add("Sheet1"); //创建新的工作薄
this.UltraWebGridExcelExporter1.Export(this.UltraWebGrid1, workbook);//将表格显示数据导出到Excel文件中
文章来自: http://sufei.cnblogs.com/
发表评论
-
控件的使用
2011-12-31 18:49 6561、AdRotator控件用法 <asp:AdRotat ... -
常用的简单算法
2011-11-17 20:38 817用二重循环实现冒泡排序 1 如何用二重循环将5个数字排序?N ... -
状态管理
2011-10-31 22:06 785内置对象方法 信息量大小 作用 ... -
现在免费的.Net空间越来越少了,我发现了个空间大,而且完全免费的
2011-10-30 12:33 10云空间-全面进入免费云时代-国内首家免费T级云空间! 云空间- ... -
Asp.Net小技巧合集
2011-09-15 18:33 83520120122 小雪 在google中找免费的电子书籍 搜索 ... -
根据数据库现有数据生成单号
2011-08-01 22:45 926/// <summary> /// ... -
FreeTextBox控件的用法
2011-08-01 22:42 1130下载网址:http://freetextbox.com/def ... -
RSS读取文章
2011-08-01 22:37 1096/// <summary> /// 加载R ... -
C#中发送Email
2011-08-01 22:29 1101// 引入命名空间 using System.Net; usi ... -
Treeview控件的用法
2011-07-31 22:30 2023//treeview控件的用法,据我现在看,以下方法在winf ... -
数据库读取和保存图片
2011-07-31 20:49 933//从数据库读取图片,并保存为11.jpg using (Sq ... -
绘制饼图
2011-07-31 20:38 639using System.Drawing; public pa ... -
WebGrid用法
2011-07-31 12:15 5242首先安装Infragistics.NetAdv ... -
封装的上传文件的方法
2011-03-19 18:24 1101//上传按钮 protected void Butt ... -
IO操作
2011-03-19 18:22 6841、創建目錄,支持多級,根據輸入的目錄地址 Director ... -
彈出提示框
2011-03-19 18:19 9531、Response.Write(“<script la ... -
report service研究
2011-03-19 18:19 1013報表服務器 Overwritedatasources ... -
Asp.net通用方法及属性
2011-03-19 17:57 8111. 在ASP.NET中专用属性: 获取服务器计算机名:P ... -
C#读写注册表操作类
2011-03-19 17:48 1255using System; using System.Coll ... -
保存DataTable的数据
2011-03-19 17:47 2225在botton的click事件中定义datatable,当cl ...
相关推荐
内容概要:本文详细介绍了参数化重采样时频变换(PRTF)在振动与声音信号故障诊断中的应用。首先通过仿真信号展示PRTF的基本原理,即通过非线性时间轴映射提高时频分辨率,特别是在处理非平稳信号时的优势。接着讨论了PRTF的具体实现步骤,包括重采样、时频分析、坐标系转换等关键技术点。文中还提供了多个实际案例,如齿轮箱故障诊断、压缩机阀片断裂检测、蝙蝠回声定位信号处理等,展示了PRTF在不同应用场景中的灵活性和有效性。此外,文章分享了一些实用经验和技巧,如窗函数选择、抗混叠滤波、多尺度融合等,帮助读者更好地理解和应用PRTF。 适合人群:具备一定MATLAB编程基础和技术背景的信号处理工程师、研究人员。 使用场景及目标:适用于处理非平稳信号,尤其是振动和声音信号的故障诊断。目标是提高时频分辨率,清晰呈现故障特征,从而快速准确定位故障源。同时,也为研究者提供了一种新的信号处理工具,拓展了传统时频分析方法的应用范围。 其他说明:PRTF虽然强大,但在某些情况下并非最佳选择,如处理稳态信号或需要极高频率分辨率的任务。因此,使用者应根据具体情况选择合适的工具。此外,由于PRTF计算量较大,实时性要求较高的场景需考虑硬件加速或其他优化手段。
基于MATLAB的汽车出入库识别系统是一份适用于毕业设计或课程设计的项目,它主要围绕车辆进出仓库的自动识别技术开发。该系统充分利用MATLAB这一强大的数学计算和图形处理软件,实现了汽车识别的核心功能。 项目主要包括以下几个关键部分: 1. **图像采集与预处理**:通过摄像头或传感器捕捉汽车的实时图像,对图像进行预处理,如灰度化、边缘检测或特征提取,提高后续识别的精度。 2. **目标检测与识别**:利用MATLAB的机器视觉工具箱,可能采用了模板匹配、特征点匹配(如SIFT、SURF或HOG)、或者现代的深度学习技术(如卷积神经网络CNN),来识别出汽车的特征。 3. **车牌识别**:针对汽车的车牌进行识别,这通常涉及到字符分割、识别和验证,可能结合了OCR(Optical Character Recognition)技术。 4. **数据分析与管理系统**:收集并分析出入库数据,用于优化仓库管理策略,如实时流量监控、车辆调度等。 5. **文档与代码完整性**:项目不仅提供了完整的工作流程和算法实现,还包含了详尽的README.md文档,以便使用者了解项目的结构和使用方法,以及注意事项。 这个系统的优势在于将理论知识应用到实际场景中,既锻炼了学生的编程能力,也展示了MATLAB在计算机视觉领域的实用性。通过下载和交流,有助于参与者提升自己的技术能力,并推动自动化仓储系统的研发和优化。
# 基于51单片机的密码锁控制器 ## 项目简介 本项目是一个基于51单片机的密码锁控制器,通过结合LCD显示器和键盘,实现了一个简单的密码输入与验证系统。该系统可以用于需要密码保护的应用场景,如门禁系统、保险箱等。用户可以通过键盘输入密码,系统会根据输入的密码进行验证,并通过LED灯显示验证结果。 ## 项目的主要特性和功能 1. LCD显示功能使用LCD显示器实时显示密码输入的相关信息。 2. 密码设置与修改用户可以设置和修改一个4位数字(09)的密码。 3. 超级用户密码系统内置一个超级用户密码“1234”,用于特殊权限操作。 4. 密码验证反馈密码输入正确时,系统会亮绿灯密码输入错误时,系统会亮红灯。 ## 安装使用步骤 ### 前提条件 假设用户已经下载了本项目的源码文件,并具备基本的单片机开发环境(如Keil等)。 ### 步骤 1. 解压源码文件将下载的源码文件解压到本地目录。
# 基于Python和强化学习算法的智能体训练系统 ## 项目简介 本项目是一个基于Python和强化学习算法的智能体训练系统,旨在通过深度学习和策略优化技术,训练智能体在复杂环境中进行决策和行动。项目结合了多种强化学习算法,如TRPO(Trust Region Policy Optimization),并使用了如Pommerman这样的复杂环境进行训练和评估。 ## 项目的主要特性和功能 强化学习算法包括TRPO在内的多种强化学习算法,适用于连续动作空间的强化学习任务。 环境模拟使用Pommerman环境进行智能体的训练和评估,环境包含复杂的棋盘布局和动态变化的炸弹、火焰等元素。 预训练与微调支持预训练模型的加载和微调,加速训练过程。 多模型评估支持多个模型的同时评估,比较不同模型在相同环境下的表现。 状态抽象与特征提取通过状态抽象和特征提取,优化智能体的决策过程。
内容概要:本文档展示了2022年中国制造业上市公司百强企业在不同城市群和城市的分布情况。从城市群角度看,百强企业主要集中在长三角(19家)、粤港澳(16家)和京津冀(11家)三大国家级城市群,这些地区凭借强大的发展基础、完善的产业链和优越的营商环境成为制造业高质量发展的领头羊。从具体城市分布来看,深圳和北京各有10家企业上榜,上海有9家。其中,深圳以比亚迪、中兴等大企业为代表,在营收规模上位居全国第一;北京依托科技和人才优势支持企业发展;上海则在高端制造业特别是集成电路领域处于领先地位。 适合人群:对中国经济地理、制造业发展趋势感兴趣的读者,以及从事相关行业研究的专业人士。 使用场景及目标:①了解中国制造业区域布局和发展趋势;②为政策制定者提供参考依据;③为企业投资决策提供数据支持。 阅读建议:建议重点关注各城市群和城市的具体数据,结合当地产业特色和发展优势进行分析,以便更好地理解中国制造业的空间分布规律及其背后的原因。
房地产营销策划 -湖南涟源博盛生态园年度营销方案.pptx
内容概要:本文详细介绍了利用粒子群算法(PSO)在Matlab中设计宽带消色差超透镜的方法及其FDTD仿真验证。首先,通过定义合理的初始参数范围和适应度函数,将超透镜的纳米结构参数(如纳米柱的直径、高度、周期)作为粒子的位置,采用PSO进行优化。适应度函数结合了预存的相位延迟查找表和实时FDTD仿真结果,确保优化过程中能够高效评估不同结构参数的效果。文中还讨论了惯性权重的动态调整、震荡因子的引入以及适应度函数中物理约束的添加,以提高优化效果并防止陷入局部最优。最终,通过FDTD仿真验证优化结果,展示了在可见光波段内的聚焦效率和焦斑尺寸的改进。 适合人群:从事光学设计、超材料研究、电磁仿真领域的科研人员和技术开发者。 使用场景及目标:适用于需要设计高性能宽带消色差超透镜的研究项目,旨在通过粒子群算法优化超透镜结构参数,减少色差并提高聚焦效率。 其他说明:文中提供了详细的Matlab代码片段和FDTD仿真设置示例,帮助读者更好地理解和实施该方法。此外,强调了在实际应用中需要注意的参数选择和物理约束,以确保设计方案的可行性和有效性。
内容概要:本文详细介绍了利用FLAC 3D软件进行深基坑支护结构的数值模拟方法,特别是针对冠梁、钢支撑和钻孔灌注桩的组合支护结构。文章首先解释了钻孔灌注桩的建模要点,强调了桩土接触面参数设置的重要性。接着讨论了钢支撑的激活时机及其对支护系统的影响,指出合理的开挖步控制可以更好地模拟实际情况。对于冠梁,则着重于其与桩顶的正确耦合方式以及弯矩分布的监测。此外,还分享了一些实用的经验教训和技术细节,如避免常见的建模错误、优化参数选择等。 适合人群:从事岩土工程、地下结构设计的专业人士,尤其是有一定FLAC 3D使用经验的研究人员和工程师。 使用场景及目标:适用于需要精确模拟深基坑开挖过程中支护结构行为的工程项目,旨在提高数值模拟的准确性,为实际施工提供科学依据和支持。 其他说明:文中提供了大量具体的FLAC 3D命令示例和实践经验,有助于读者快速掌握相关技能并在实践中灵活运用。同时提醒读者关注模型验证的重要性,确保模拟结果能够真实反映工程实际状况。
前端铺子开发者 前端杂货铺 小程序在线课堂+工具组件小程序uniapp移动端
Delphi 12.3控件之geniso(CD iso Generator)可启动光盘文件制作器可执行文件.zip
# 基于Arduino的传感器应用项目 ## 项目简介 这是一个基于Arduino开发的项目集合,主要聚焦于传感器应用及相关开发。通过此项目,您将能够了解并实践如何使用Arduino进行硬件编程,以实现对各种传感器的读取和控制。 ## 项目的主要特性和功能 ### 1. 传感器读取 此项目包含多个示例,可以读取不同类型的传感器数据,如温度、湿度、光线、压力等。 ### 2. 实时数据反馈 通过Arduino,项目能够实现实时读取传感器的数据并在某些媒介(如LED灯、LCD显示屏等)上进行反馈。 ### 3. 自动化控制 根据项目需求,可以实现基于传感器数据的自动化控制,例如自动开关灯光、调节风扇速度等。 ## 安装使用步骤 ### 1. 下载源码文件 ### 2. 安装Arduino IDE 确保您的计算机上安装了Arduino IDE,这是编写和上传代码到Arduino设备所必需的。 ### 3. 导入项目文件
房地产活动策划 -2025商业地产脆皮打工人春日养生局(万物回春主题)活动策划方案.pptx
该资源为h5py-3.1.0-cp37-cp37m-manylinux1_x86_64.whl,欢迎下载使用哦!
内容概要:本文详细介绍了利用Comsol软件进行远场涡流检测仿真的方法和技术要点。首先构建了一个二维轴对称模型,模拟了线圈和含缺陷铁磁管道之间的相互作用。文中强调了空气域大小、材料参数设置以及频率选择对检测效果的重要影响。通过调整不同的仿真参数如频率、线圈位置等,探讨了它们对磁场强度和相位变化的影响规律。此外,还分享了一些提高仿真效率的经验,例如合理的网格划分策略和参数化扫描的应用。最后指出远场涡流检测在工业探伤领域的潜在价值,特别是在检测埋地管道内部缺陷方面的优势。 适合人群:从事无损检测、电磁场仿真等相关工作的科研人员和技术工程师。 使用场景及目标:适用于希望深入了解远场涡流检测原理并掌握具体实施步骤的研究者;旨在为实际工程项目提供理论支持和技术指导。 其他说明:文中提供了大量实用的操作技巧和注意事项,有助于读者快速上手并在实践中优化自己的仿真流程。
# 基于STM32F10x微控制器的综合驱动库 ## 项目简介 本项目是一个基于STM32F10x系列微控制器的综合驱动库,旨在为开发者提供一套全面、易于使用的API,用于快速搭建和配置硬件资源,实现高效、稳定的系统功能。项目包含了STM32F10x系列微控制器的基本驱动和常用外设(如GPIO、SPI、Timer、RTC、ADC、CAN、DMA等)的驱动程序。 ## 项目的主要特性和功能 1. 丰富的外设驱动支持支持GPIO、SPI、Timer、RTC、ADC、CAN、DMA等外设的初始化、配置、读写操作和中断处理。 2. 易于使用的API接口提供统一的API接口,简化外设操作和配置,使开发者能够专注于应用程序逻辑开发。 3. 全面的时钟管理功能支持系统时钟、AHB时钟、APB时钟的生成和配置,以及时钟源的选择和配置。 4. 电源管理功能支持低功耗模式、电源检测和备份寄存器访问,帮助实现节能和延长电池寿命。
MACHIN3tools_1.0.1
内容概要:本文详细介绍了丰田功率分流混合动力系统(如普锐斯)的Simulink分析模型及其经济性和动力性仿真的全过程。首先解析了该系统独特的双电机加发动机构型以及行星排耦合机制,接着阐述了Simulink模型的具体构建步骤,包括初始化参数设定、各模块的选择与配置。文中提供了多个代码示例,展示如何模拟不同工况下的动力输出和能耗情况,并强调了模型的高精度和实用性。此外,还探讨了模型的可扩展性和版本兼容性,以及一些关键的技术细节,如行星齿轮参数设定、能量管理模式、能耗计算方法等。 适合人群:从事混合动力技术研发的工程师和技术爱好者,尤其是对丰田THS系统感兴趣的读者。 使用场景及目标:①用于研究和开发新型混合动力系统;②为现有混合动力系统的改进提供参考;③作为教学工具,帮助学生理解和掌握混合动力系统的工作原理和仿真技术。 其他说明:该模型基于MATLAB 2021a版本构建,具有良好的版本兼容性和模块化设计,便于参数调整和功能扩展。同时,模型经过严格的验证,确保仿真结果与实际情况高度一致。
# 基于Vue 3和Element Plus框架的Vite前端快速开发工程 ## 项目简介 本项目是一个基于Vue 3和Element Plus框架的项目模板,运用Vite作为前端开发工具,集成了Vue Composition API、Vue Router等常用技术栈。其目的在于简化前端开发流程,提升开发效率,提供了路由系统、组件自动化加载、状态管理、布局系统、CSS引擎等丰富功能,同时支持国际化、API自动加载,还集成了单元测试、端到端测试以及可视化调试与预览等功能。 ## 项目的主要特性和功能 1. 基于Vue 3和Element Plus构建,具备丰富组件库和UI样式。 2. 采用Vite开发工具,支持快速开发迭代。 3. 基于文件的路由系统,便于页面管理。 4. 组件自动化加载,简化开发流程。 5. 使用Pinia进行状态管理,方便应用状态维护。 6. 布局系统,方便页面布局管理。 7. 支持UnoCSS高性能即时原子化CSS引擎。
upload2025.04.17-2.zip
内容概要:本文详细介绍了利用Matlab和CasADi库实现四旋翼飞行器的模型预测控制(MPC)仿真的全过程。首先建立了四旋翼飞行器的动力学模型,采用12维状态向量表示系统状态,并通过离散化方法将连续时间模型转化为离散时间模型。接着,构建了MPC的优化问题,包括目标函数的设计以及各种约束条件的设定。为了提高求解效率,采用了自动微分技术和IPOPT求解器。此外,文中还讨论了一些实用技巧,如姿态环使用四元数修正、引入风速扰动测试鲁棒性和支持复杂轨迹导入等。最终实现了对四旋翼飞行器的有效轨迹跟踪和姿态控制。 适合人群:对无人飞行器控制系统感兴趣的研究人员和技术爱好者,尤其是熟悉Matlab编程并希望深入了解MPC算法的人士。 使用场景及目标:适用于研究和开发四旋翼飞行器的高级控制策略,旨在提升飞行器的自主导航能力和应对环境变化的能力。通过该仿真平台,研究人员能够验证不同控制算法的效果,并为实际硬件部署提供理论依据。 其他说明:随附的PPT提供了详细的数学推导和稳定性分析,有助于加深对MPC原理的理解。同时,完整的源代码可供下载,便于进一步修改和扩展。