问题描述
c#怎样导入导出excel表?(最好提供一个示例代码及教程)
解决方案
解决方案二:
可以引用EXCEL的Com控件,但很麻烦。网上很多第三方操作的控件,自己可以找一下,比如Aspose.Cell,FarPoint,等
解决方案三:
先要添加com控件,然后才能使用。以下是我做的一个系统输出到Execl表格的代码,供你参考:privatevoidtoolStripButton_print_Click(objectsender,EventArgse){intRCount=dataGridView1.Rows.Count;intCCount=dataGridView1.Columns.Count;//从工具箱中添加一个“保存”对话框saveFileDialog1.DefaultExt="xls";saveFileDialog1.Filter="EXCEL文件(*.xls)|*.xls";//EXcel文件名称saveFileDialog1.FileName="横向课题信息表";saveFileDialog1.InitialDirectory=Directory.GetCurrentDirectory();//取消if(saveFileDialog1.ShowDialog()==DialogResult.Cancel){return;}stringfileNameString=saveFileDialog1.FileName;if(fileNameString.Length==0){MessageBox.Show("文件名不能为空!");return;}FileInfofile=newFileInfo(fileNameString);if(file.Exists){/*if(MessageBox.Show("文件已存在,要替换吗?","提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question)==DialogResult.Cancel){return;}*/try{file.Delete();}catch(Exceptionex){MessageBox.Show(ex.Message,"异常",MessageBoxButtons.OK,MessageBoxIcon.Error);return;}}//注意引用的添加Excel.ApplicationobjExcel=null;Excel.WorkbookobjWorkbook=null;Excel.Worksheetobjsheet=null;try{objExcel=newExcel.Application();objWorkbook=objExcel.Workbooks.Add(Type.Missing);objsheet=(Excel.Worksheet)objWorkbook.ActiveSheet;objExcel.Visible=true;Excel.Rangemyrang13=objsheet.get_Range(objExcel.Cells[2,1],objExcel.Cells[1,8]);myrang13.Font.Bold=true;myrang13.Font.Size="18";objExcel.Cells[1,8]="横向课题信息";objExcel.Cells[2,1]="打印日期:"+DateTime.Now.ToShortDateString();//向Excel中写入表格的表头intdisplayColumnsCount=1;for(inti=0;i<=dataGridView1.ColumnCount-1;i++){if(dataGridView1.Columns[i].Visible==true){objExcel.Cells[3,displayColumnsCount]=dataGridView1.Columns[i].HeaderText.Trim();displayColumnsCount++;}}//向Excel中写入数据for(introw=0;row<=dataGridView1.RowCount-1;row++){displayColumnsCount=1;for(intcol=0;col<CCount;col++){if(dataGridView1.Columns[col].Visible==true){try{stringvalue;if(col==4||col==7||col==11||col==12||col==14||col==16||col==18||col==20){value="'"+this.dataGridView1.Rows[row].Cells[col].Value.ToString().Trim();}elsevalue=this.dataGridView1.Rows[row].Cells[col].Value.ToString().Trim();objExcel.Cells[row+4,displayColumnsCount]=value;//objExcel.Cells[row+4,displayColumnsCount]=this.dataGridView1.Rows[row].Cells[col].Value.ToString().Trim();displayColumnsCount++;}catch(Exception){}}}}objWorkbook.SaveAs(fileNameString,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlSaveAsAccessMode.xlShared,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);}catch(Exceptionex){MessageBox.Show(ex.Message,"异常",MessageBoxButtons.OK,MessageBoxIcon.Error);return;}finally{//关闭Excel应用if(objWorkbook!=null)objWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);if(objExcel.Workbooks!=null)objExcel.Workbooks.Close();if(objExcel!=null)objExcel.Quit();objsheet=null;objWorkbook=null;objExcel=null;}MessageBox.Show(fileNameString+"nn导出完毕!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);}
解决方案四:
也可以不用添加excel引用,而是直接用流来实现:privatevoidbutton3_Click(objectsender,EventArgse){SaveFileDialogsaveFileDialog=newSaveFileDialog();saveFileDialog.Filter="Execlfiles(*.xls)|*.xls";saveFileDialog.FilterIndex=0;saveFileDialog.RestoreDirectory=true;saveFileDialog.CreatePrompt=true;saveFileDialog.Title="ExportExcelFileTo";if(saveFileDialog.ShowDialog()==DialogResult.OK){StreammyStream;myStream=saveFileDialog.OpenFile();StreamWritersw=newStreamWriter(myStream,System.Text.Encoding.GetEncoding(-0));stringstr="";try{//写标题for(inti=0;i<dataGridView1.ColumnCount;i++){if(i>0){str+="t";}str+=dataGridView1.Columns[i].HeaderText;}sw.WriteLine(str);//写内容for(intj=0;j<dataGridView1.Rows.Count;j++){stringtempStr="";for(intk=0;k<dataGridView1.Columns.Count;k++){if(k>0){tempStr+="t";}tempStr+=dataGridView1.Rows[j].Cells[k].Value.ToString();}sw.WriteLine(tempStr);}sw.Close();myStream.Close();}catch(Exceptionex){MessageBox.Show(ex.ToString());}finally{sw.Close();myStream.Close();}}}
//数据放在datagridview中,如果不需要datagridview则可直接放在dataset中,若用datagridview需加上这两句dataGridView1.AllowUserToAddRows=false;//在datagridview中不显示最下面带*的行dataGridView1.AllowUserToDeleteRows=false;//不允许用户删除行这两行
解决方案五:
楼上两位正解。
解决方案六:
这里有一个可以直接使用的导出Excel的方法,用html填充资料的publicvoidExportToExcel(DataTabledt){Response.Clear();Response.Buffer=true;Response.Charset="UTF-8";Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls");Response.ContentEncoding=System.Text.Encoding.GetEncoding("UTF-8");Response.Write("<html><head><metahttp-equiv=Content-Typecontent="text/html;charset=utf-8">");Response.ContentType="application/ms-excel";this.EnableViewState=false;stringcolHeaders="";intcolCount=dt.Columns.Count-1;StringBuildersb=newStringBuilder();colHeaders="<tablestyle="FONT-SIZE:15px"border="1">";sb.Append(colHeaders);sb.Append("<tr>");for(inti=0;i<=colCount;i++){sb.Append("<tdalign=middle>");sb.Append(dt.Columns[i].ColumnName.ToString());sb.Append("</td>");}sb.Append("</tr>");for(inti=0;i<dt.Rows.Count;i++){sb.Append("<tralign=left>");for(intj=0;j<=colCount;j++){sb.Append("<td>");sb.Append(BlankString(dt.Rows[i][j].ToString().Trim()));//sb.Append(dt.Rows[i][j].ToString());sb.Append("</td>");}sb.Append("</tr>");}colHeaders=sb.ToString();colHeaders=colHeaders+"n";Response.Write(colHeaders);Response.Write("</body></html>");Response.End();}
解决方案七:
引用5楼l1314j的回复:
这里有一个可以直接使用的导出Excel的方法,用html填充资料的publicvoidExportToExcel(DataTabledt){Response.Clear();Response.Buffer=true;Response.Charset="UTF-8";Response.AppendHeader("Content-Disposition","……
不需要添加引用
解决方案八:
学习.............................
解决方案九:
.Net组件里面有Microsoft.Office.Interop.Excel,在引用里加进去,并using一下。就可以用Microsoft.Office.Interop.Excel.Application对象了