Bless
2017-05-16 17:11
采纳率: 100%
浏览 2.5k

C# 怎么建立Excel表格?

我想生成个Excel表,手机敲的方法哪里格式不对请见谅,纯自学,无知小白自造工具办公,请多帮忙,谢谢!

//listname是列名,Path是路径
public void new_Excel(string[] listname,string Path)

//要生成Excel表格,不要workbook之类的,不好读,我经常用SQL语句查表格,就是不知道怎么建立。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • HeRo_OO7 2017-05-17 13:28
    已采纳

    下面的例子你可以借鉴下,是Access里面数据导出成Excel

            OleDbConnection con = new OleDbConnection();
                        string TABLE=string.Empty;//表名
            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.Filter = ("Excel 文件(*.xls)|*.xls");//指定文件后缀名为Excel 文件。   
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    string filename = saveFile.FileName;
                    if (System.IO.File.Exists(filename))
                    {
                        //System.IO.File.Delete(filename);//如果文件存在删除文件。   
                        MessageBox.Show("存在同名Excel文件,请用户重新命名...");
                    }
                    int index = filename.LastIndexOf("\\");//获取最后一个\的索引   
                    filename = filename.Substring(index + 1);//获取excel名称(新建表的路径相对于SaveFileDialog的路径)   
                    //select * into 建立 新的表。   
                    //[[Excel 8.0;database= excel名].[sheet名] 如果是新建sheet表不能加$,如果向sheet里插入数据要加$.    
                    //sheet最多存储65535条数据。   
                    string sql1 = "select top 65535 ID as 序号ID,NAME as 姓名,AGE as 年龄 into [Excel 8.0;database=" + filename + "].[明细] from ";
                    string sql = sql1 + TABLE;
                    con.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + Application.StartupPath + "\\data007.mdb";//将数据库放到debug目录下。   
                    OleDbCommand com = new OleDbCommand(sql, con);
                    con.Open();
                    com.ExecuteNonQuery();
    
                    MessageBox.Show("导出数据成功", "导出数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                con.Close();
            }  
    
    点赞 评论
  • Bless 2017-05-16 17:21

    求大神帮我完成这个方法

    点赞 评论
  • 下载C#版本的NPOI.dll这组件,然后添加引用,使用下面代码就可以导出了

     using System.IO;
    using System.Web;
    using System.Data;
    using NPOI.HSSF.Util;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.Collections;
    /// <summary>
    /// 下载信息url的html内容的类
    /// </summary>
    public class OutputExcel
    {
        public static void BuildExcel(DataTable dt)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
    
    
            ICellStyle styleCell = hssfworkbook.CreateCellStyle();
            styleCell.FillPattern = FillPattern.SolidForeground;
            styleCell.FillForegroundColor = HSSFColor.Grey25Percent.Index;
            styleCell.Alignment = HorizontalAlignment.Center;
            IFont ifont = hssfworkbook.CreateFont();
            ifont.Boldweight = (short)FontBoldWeight.Bold;
            ifont.Color = HSSFColor.Red.Index;
            styleCell.SetFont(ifont);
    
            int colLen = dt.Columns.Count,i,j=1;
            IRow row = sheet1.CreateRow(0);
            ICell cell;
            string[] dtCols = new string[colLen];
            //标题
            for (i = 0; i < colLen; i++)
            {
                dtCols[i] = dt.Columns[i].ColumnName;
                cell = row.CreateCell(i);
                cell.SetCellValue(dtCols[i]);
                sheet1.SetColumnWidth(i, 15 * 256);
                cell.CellStyle = styleCell;
            }
    
            string fn = dt.TableName;
    
            foreach (DataRow dr in dt.Rows)
            {
                row = sheet1.CreateRow(j);
                for (i = 0; i < colLen; i++)
                {
    
                    cell = row.CreateCell(i);
                    cell.SetCellValue(dr[i].ToString());
                }
                j++;
            }
    
           //c/s系统的,如果你是c/s,MemoryStream file = new MemoryStream();这句改为你的文件流,写入文件
            HttpContext context = HttpContext.Current;
            if (context.Request.UserAgent.IndexOf("Trident/") != -1) fn = HttpUtility.UrlEncode(fn, System.Text.Encoding.UTF8) + ".xls";
            else fn = fn + ".xls";
    
            context.Response.Clear();
            context.Response.ContentType = "application/vnd.ms-excel";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", fn));
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            context.Response.BinaryWrite(file.GetBuffer());
            context.Response.End();
        }
    }
    
    点赞 评论
  • BloodyMandoo 2017-05-17 01:20

    可以看看这个博客上写的http://blog.okbase.net/csharp/archive/4481.html

    点赞 评论
  • ouylvr 2017-05-17 03:30
    点赞 评论

相关推荐 更多相似问题