zoukankan      html  css  js  c++  java
  • Excel常用操作

    Excel常用操作

    1 读取Excel到DataTable

     一般读取Excel需要指定sheet名称,当需要批量处理excel文件的时候,而且每个excel的sheet名称又不一样的时候,导入就成了一件恼火的事情。

    先提高一个自动获取sheet名称的功能。

    来看看代码实现 :

    复制代码
      OleDbConnection con = new OleDbConnection(GetConn(tempxlsPath));

      DataTable dtSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

      sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString();

    复制代码

    有人说:外部文件不是有效的Excel文件,没关系,是应该office版本的文件,导致连接串有变化。

    复制代码

    private string GetConn(string xlsPath)
    {
      if (!File.Exists(xlsPath))
      {
        return "指定的Excel文件不存在!";
      }
      return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";
    }

    private string GetConnACE(string xlsPath)
    {
      if (!File.Exists(xlsPath))
      {
        return "指定的Excel文件不存在!";
      }
      return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";
    }

    OleDbConnection con = new OleDbConnection(GetConn(tempxlsPath));

    //读取
    try
    {
      con.Open();
    }
    catch
    {
      con.ConnectionString = GetConnACE(tempxlsPath);
      try
      {
        con.Open();
      }
      catch(Exception ex)
      {
        retmsg = ex.Message;
        return dtExcel;
      }
    }

    复制代码

    当遇到Excel不是标准的Excel时,如网页下载的基于html格式或csv格式的文件,连接查询就会报错,这是就需要另存为标准的格式:

    复制代码

        Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;

        ObjWorkBook = ObjExcel.Workbooks.Open(xlsPath, 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);


        tempxlsPath = System.IO.Path.GetDirectoryName(xlsPath) + "\\" + DateTime.Now.Ticks.ToString() + ".xls";

        ((Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1]).SaveAs(tempxlsPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, false, false, false, Type.Missing, Type.Missing, true);

        ObjWorkBook.Close(false, Type.Missing, Type.Missing);
        ObjExcel.Quit();
        retmsg = KillSpecialExcel(ObjExcel);

      [DllImport("user32.dll", SetLastError = true)]
      static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
      private string KillSpecialExcel(Microsoft.Office.Interop.Excel.Application objExcel)
      {
        try
        {
          if (objExcel != null)
          {
            int lpdwProcessId;
            GetWindowThreadProcessId(new IntPtr(objExcel.Hwnd), out lpdwProcessId);

            System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
          }
        }
        catch (Exception ex)
        {
          return "Delete Excel Process Error:" + ex.Message;
        }
        return "";
      }

    复制代码

    下面是 读取Excel完整代码:

    复制代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.OleDb;
    using System.IO;
    using System.Runtime.InteropServices;

    namespace ExcelLib
    {
    /// <summary>
    /// 读取Excel文件到DataTable
    /// </summary>
    public class XlsRead
    {
    /// <summary>
    /// 从Excel导入数据到DataTable
    /// </summary>
    /// <param name="xlsPath">xls文件路径</param>
    /// <param name="sheetName">工作区名称,为空自动获取第一个</param>
    /// <param name="needSaveAsExcel97">是否另存为标准Excel2003-97</param>
    /// <param name="delxls">是否删除Excel文件</param>
    /// <param name="retmsg">返回信息</param>
    /// <returns>返回结果 DataTable</returns>
    public DataTable GetDataTable(string xlsPath, string sheetName, bool needSaveAsExcel97, bool delxls, out string retmsg)
    {
    retmsg = "";

    string tempxlsPath = xlsPath;

    DataTable dtExcel = new DataTable();

    if (needSaveAsExcel97)
    {
    Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;

    ObjWorkBook = ObjExcel.Workbooks.Open(xlsPath, 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);


    tempxlsPath = System.IO.Path.GetDirectoryName(xlsPath) + "\\" + DateTime.Now.Ticks.ToString() + ".xls";

    ((Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1]).SaveAs(tempxlsPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, false, false, false, Type.Missing, Type.Missing, true);

    ObjWorkBook.Close(false, Type.Missing, Type.Missing);
    ObjExcel.Quit();
    retmsg = KillSpecialExcel(ObjExcel);
    }

    OleDbConnection con = new OleDbConnection(GetConn(tempxlsPath));

    //读取
    try
    {
    con.Open();
    }
    catch
    {
    con.ConnectionString = GetConnACE(tempxlsPath);
    try
    {
    con.Open();
    }
    catch(Exception ex)
    {
    retmsg = ex.Message;
    return dtExcel;
    }
    }

    if (string.IsNullOrEmpty(sheetName))
    {
    DataTable dtSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

    sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString();

    if (string.IsNullOrEmpty(sheetName))
    {
    retmsg = "未找到数据源";
    return dtExcel;
    }
    }

    OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [" + sheetName + "]", con);
    adapter.FillSchema(dtExcel, SchemaType.Mapped);
    adapter.Fill(dtExcel);
    con.Close();
    dtExcel.TableName = sheetName;

    if (dtExcel.Rows.Count == 0)
    {
    retmsg = "Excel无数据";

    if (needSaveAsExcel97 && File.Exists(tempxlsPath))
    {
    File.Delete(tempxlsPath);
    }
    return dtExcel;
    }
    else
    {
    if (needSaveAsExcel97 && File.Exists(tempxlsPath))
    {
    File.Delete(tempxlsPath);
    }
    if (delxls && File.Exists(xlsPath))
    {
    File.Delete(xlsPath);
    }
    }
    return dtExcel;
    }


    private string GetConn(string xlsPath)
    {
    if (!File.Exists(xlsPath))
    {
    return "指定的Excel文件不存在!";
    }
    return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";

    }

    private string GetConnACE(string xlsPath)
    {
    if (!File.Exists(xlsPath))
    {
    return "指定的Excel文件不存在!";
    }
    return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + xlsPath + ";Extended properties=\"Excel 8.0;IMEX=1;HDR=YES;\"";
    }

    [DllImport("user32.dll", SetLastError = true)]
    static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
    private string KillSpecialExcel(Microsoft.Office.Interop.Excel.Application objExcel)
    {
    try
    {
    if (objExcel != null)
    {
    int lpdwProcessId;
    GetWindowThreadProcessId(new IntPtr(objExcel.Hwnd), out lpdwProcessId);

    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
    }
    }
    catch (Exception ex)
    {
    return "Delete Excel Process Error:" + ex.Message;
    }
    return "";
    }
    }
    }

    复制代码

    以下是 Excel 批量导出的代码,需要几个Dll,都包含在附件中:

    复制代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Collections;
    using org.in2bits.MyXls;
    using ICSharpCode.SharpZipLib.Zip;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System.Data;

    namespace ExcelLib
    {
    /// <summary>
    /// 导出EXCEL类
    /// </summary>
    public class XlsExport
    {
    private string tempPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Temp" + Path.DirectorySeparatorChar;

    /// <summary>
    /// 构造函数,自动创建Temp文件夹
    /// </summary>
    public XlsExport()
    {
    if (!Directory.Exists(tempPath))
    {
    Directory.CreateDirectory(tempPath);
    }
    }

    private string exportname = "";

    /// <summary>
    /// 枚举导出文件类型
    /// </summary>
    public enum FileType
    {
    /// <summary>
    /// Excel文件
    /// </summary>
    xls=1,
    /// <summary>
    /// pdf文件
    /// </summary>
    pdf=2,
    /// <summary>
    /// txt文本文件
    /// </summary>
    txt=3,
    /// <summary>
    /// doc文档文件
    /// </summary>
    doc=4,
    /// <summary>
    /// html网页文件
    /// </summary>
    html=5
    }

    /// <summary>
    /// 导出数据
    /// </summary>
    /// <param name="dt">DataTable数据集</param>
    /// <param name="ftype">文件类型</param>
    /// <param name="fileName">导出文件名称 默认为时间Tick</param>
    /// <returns>返回 文件路径</returns>
    public string Export(DataTable dt, FileType ftype,string fileName)
    {
    if (string.IsNullOrEmpty(fileName))
    exportname = System.DateTime.Now.Ticks.ToString();
    else
    exportname = fileName;

    ArrayList inputlist = new ArrayList();
    ArrayList thislist = new ArrayList();
    for (int i = 0; i < dt.Columns.Count; i++)
    {
    thislist.Add(dt.Columns[i].ColumnName);
    }
    inputlist.Add(thislist);

    foreach (DataRow dr in dt.Rows)
    {
    thislist = new ArrayList();
    for (int c = 0; c < dt.Columns.Count; c++)
    {
    thislist.Add(dr[dt.Columns[c].ColumnName].ToString());
    }
    inputlist.Add(thislist);
    }
    return Export(inputlist, ftype);
    }

    private string Export(ArrayList input, FileType ftype)
    {
    if ((int)ftype == 1)
    {
    return excelarraylist(input);
    }
    if ((int)ftype == 2)
    {
    return pdfarraylist(input);
    }
    if ((int)ftype == 3)
    {
    return txtarraylist(input);
    }
    if ((int)ftype == 4)
    {
    return docarraylist(input);
    }
    if ((int)ftype == 5)
    {
    return htmlarraylist(input);
    }
    return "";
    }

    private string excelarraylist(ArrayList input)//生成excel,每50000条数据生成一个xls文件,超过两个xls则打包为zip文件,只有一个xls则直接返回xls文件
    {
    ArrayList filelist = new ArrayList();
    string strFullPathAndName = exportname + "_0.xls";

    if(File.Exists(tempPath + strFullPathAndName))
    {
    return "Excel文件已存在。";
    }

    filelist.Add(strFullPathAndName);
    XlsDocument xls = new XlsDocument();
    xls.FileName = tempPath + strFullPathAndName;
    Worksheet sheet = xls.Workbook.Worksheets.Add(exportname);//状态栏标题名称
    Cells cells = sheet.Cells;
    int col_length = 0;
    int file_i = 0;
    int count_i = 0;
    for (int i = 0; i < input.Count; i++)
    {
    if (i % 50000 == 0 && i > 0)//达到50000个,生成下一个文件
    {
    xls.Save();
    file_i++;
    count_i = 0;
    strFullPathAndName = exportname + "_" + file_i + ".xls";
    filelist.Add(strFullPathAndName);
    xls = new XlsDocument();
    xls.FileName = tempPath + strFullPathAndName;
    sheet = xls.Workbook.Worksheets.Add(exportname);//状态栏标题名称
    cells = sheet.Cells;
    col_length = 0;
    }
    ArrayList this_list = (ArrayList)input[i];
    col_length = this_list.Count;
    for (int j = 0; j < this_list.Count; j++)
    {
    Cell cell = cells.Add(count_i + 1, j + 1, this_list[j]);
    if (i == 0)
    {
    cell.Font.Bold = true; //字体为粗体
    cell.Pattern = 1;
    cell.PatternColor = Colors.Silver;
    cell.TopLineStyle = 2;
    cell.TopLineColor = Colors.Black;
    }
    if (count_i == 0)
    {
    cell.LeftLineStyle = 2;
    cell.LeftLineColor = Colors.Black;
    }
    if (count_i == input.Count - 1 || count_i == 50000 - 1)
    {
    cell.RightLineStyle = 2;
    }
    else
    {
    cell.RightLineStyle = 1;
    }
    cell.RightLineColor = Colors.Black;
    if (count_i == input.Count - 1 || count_i == 50000 - 1)
    {
    cell.BottomLineStyle = 2;
    cell.BottomLineColor = Colors.Black;
    }
    }
    count_i++;
    }
    xls.Save();
    if (filelist.Count == 1)//只有一个xls文件,直接返回xls文件
    {
    return tempPath + strFullPathAndName;
    }
    else//超过一个xls文件,打包生成zip文件
    {
    MemoryStream ms = null;
    ms = new MemoryStream();
    ZipOutputStream zos = new ZipOutputStream(ms);
    string folder_name = DateTime.Now.Ticks.ToString();
    string filename = exportname + ".zip";
    FileStream fileStreamOut = new FileStream(tempPath + filename, FileMode.Create, FileAccess.Write);
    ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut);
    byte[] buffer = new byte[32];
    for (int i = 0; i < filelist.Count; i++)
    {
    string SrcFile = tempPath + filelist[i].ToString();
    FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
    ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile));
    zipOutStream.PutNextEntry(entry);
    int size;
    do
    {
    size = fileStreamIn.Read(buffer, 0, buffer.Length);
    zipOutStream.Write(buffer, 0, size);
    } while (size > 0);
    fileStreamIn.Close();
    }
    zos.Finish();
    zos.Close();
    zipOutStream.Close();
    fileStreamOut.Close();
    for (int i = 0; i < filelist.Count; i++)
    {
    File.Delete(tempPath + filelist[i].ToString());
    }

    return tempPath + filename;
    //HttpContext.Current.Response.Buffer = true;
    //HttpContext.Current.Response.Clear();//清除缓冲区所有内容
    //HttpContext.Current.Response.ContentType = "application/octet-stream";
    //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    //HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + filename));
    //HttpContext.Current.Response.Flush();
    //File.Delete(HttpContext.Current.Server.MapPath("tmp/" + filename));
    //HttpContext.Current.Response.End();
    }
    }
    private string pdfarraylist(ArrayList input)
    {
    if (!File.Exists(tempPath + "msyh.ttf"))
    {
    if (!File.Exists(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "msyh.ttf"))
    return "导入失败,msyh.ttf文件不存在,将文件放于Temp目录下后重试!";
    else
    File.Copy(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "msyh.ttf", tempPath + "msyh.ttf");
    }
    try
    {
    string strFullPathAndName = exportname + ".pdf";
    if (File.Exists(tempPath + strFullPathAndName))
    {
    return "pdf文件已存在。";
    }
    Document document = new Document();
    PdfWriter.GetInstance(document, new FileStream(tempPath + strFullPathAndName, FileMode.Create));
    document.Open();
    BaseFont titleChinese = BaseFont.CreateFont(tempPath+"msyh.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    BaseFont commonChinese = BaseFont.CreateFont(tempPath + "msyh.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    iTextSharp.text.Font tChinese = new iTextSharp.text.Font(titleChinese, 12);
    iTextSharp.text.Font cChinese = new iTextSharp.text.Font(commonChinese, 10);
    document.Add(new Paragraph(exportname, tChinese));
    //iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("xxx.jpg"));
    //document.Add(jpeg);
    int colnum = 1;
    ArrayList thislist = (ArrayList)input[0];
    colnum = thislist.Count;
    PdfPTable table = new PdfPTable(colnum);
    for (int i = 0; i < input.Count; i++)
    {
    thislist = (ArrayList)input[i];
    iTextSharp.text.Font thisfont = cChinese;
    if (i == 0)
    {
    thisfont = tChinese;
    }
    for (int j = 0; j < thislist.Count; j++)
    {
    Phrase this_phrase = new Phrase(thislist[j].ToString(), thisfont);
    iTextSharp.text.pdf.PdfPCell cell = new PdfPCell(this_phrase);
    if (i == 0)
    {
    cell.HorizontalAlignment = Element.ALIGN_CENTER;
    cell.BackgroundColor = BaseColor.GRAY;
    }
    table.AddCell(cell);
    }
    }
    document.Add(table);
    document.Close();

    return tempPath + strFullPathAndName;
    }
    catch (Exception ex)
    {
    return "导入失败:" + ex.Message;
    }
    }

    private string txtarraylist(ArrayList input)
    {
    string strFullPathAndName = exportname + ".txt";
    if (File.Exists(tempPath + strFullPathAndName))
    {
    return "txt文件已存在。";
    }
    StreamWriter writer = new StreamWriter(tempPath + strFullPathAndName, false, Encoding.UTF8);
    for (int i = 0; i < input.Count; i++)
    {
    ArrayList thislist = (ArrayList)input[i];
    string thisline = "";
    for (int j = 0; j < thislist.Count; j++)
    {
    if (thisline != "")
    {
    thisline += '\t';
    }
    thisline += thislist[j].ToString();
    }
    writer.WriteLine(thisline);
    }
    writer.Close();

    return tempPath + strFullPathAndName;

    //string filename = HttpUtility.UrlEncode(exportname + ".txt", Encoding.UTF8);
    //HttpContext.Current.Response.Buffer = true;
    //HttpContext.Current.Response.Clear();//清除缓冲区所有内容
    //HttpContext.Current.Response.ContentType = "application/octet-stream";
    //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    //HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
    //HttpContext.Current.Response.Flush();
    //File.Delete(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
    //HttpContext.Current.Response.End();
    }

    private string docarraylist(ArrayList input)
    {
    string strFullPathAndName = exportname + ".doc";
    if (File.Exists(tempPath + strFullPathAndName))
    {
    return "doc文件已存在。";
    }
    StreamWriter writer = new StreamWriter(tempPath + strFullPathAndName, false, Encoding.UTF8);
    writer.WriteLine("<html>");
    writer.WriteLine("<body style='font-size:12px'>");
    writer.WriteLine("<table border='2' width='100%'>");
    for (int i = 0; i < input.Count; i++)
    {
    ArrayList thislist = (ArrayList)input[i];
    writer.WriteLine("<tr>");
    for (int j = 0; j < thislist.Count; j++)
    {
    if (i == 0)
    {
    writer.WriteLine("<th>" + thislist[j].ToString() + "</th>");
    }
    else
    {
    writer.WriteLine("<td>" + thislist[j].ToString() + "</td>");
    }

    }
    writer.WriteLine("</tr>");
    }
    writer.WriteLine("</table>");
    writer.WriteLine("</body>");
    writer.WriteLine("</html>");
    writer.Close();
    return tempPath + strFullPathAndName;

    //string filename = HttpUtility.UrlEncode(exportname + ".doc", Encoding.UTF8);
    //HttpContext.Current.Response.Buffer = true;
    //HttpContext.Current.Response.Clear();//清除缓冲区所有内容
    //HttpContext.Current.Response.ContentType = "application/octet-stream";
    //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    //HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
    //HttpContext.Current.Response.Flush();
    //File.Delete(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
    //HttpContext.Current.Response.End();
    }

    private string htmlarraylist(ArrayList input)
    {
    string strFullPathAndName = exportname + ".html";
    if (File.Exists(tempPath + strFullPathAndName))
    {
    return "html文件已存在。";
    }
    StreamWriter writer = new StreamWriter(tempPath + strFullPathAndName, false, Encoding.UTF8);
    writer.WriteLine("<html>");
    writer.WriteLine("<body style='font-size:12px'>");
    writer.WriteLine("<table border='2' width='100%'>");
    for (int i = 0; i < input.Count; i++)
    {
    ArrayList thislist = (ArrayList)input[i];
    writer.WriteLine("<tr>");
    for (int j = 0; j < thislist.Count; j++)
    {
    if (i == 0)
    {
    writer.WriteLine("<th>" + thislist[j].ToString() + "</th>");
    }
    else
    {
    writer.WriteLine("<td>" + thislist[j].ToString() + "</td>");
    }

    }
    writer.WriteLine("</tr>");
    }
    writer.WriteLine("</table>");
    writer.WriteLine("</body>");
    writer.WriteLine("</html>");
    writer.Close();
    return tempPath + strFullPathAndName;
    //string filename = HttpUtility.UrlEncode(exportname + ".html", Encoding.UTF8);
    //HttpContext.Current.Response.Buffer = true;
    //HttpContext.Current.Response.Clear();//清除缓冲区所有内容
    //HttpContext.Current.Response.ContentType = "application/octet-stream";
    //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    //HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
    //HttpContext.Current.Response.Flush();
    //File.Delete(HttpContext.Current.Server.MapPath("tmp/" + strFullPathAndName));
    //HttpContext.Current.Response.End();
    }
    }
    }

    复制代码

    加个附件真麻烦,不过还是加上了。

    ExcelLib.zip

  • 相关阅读:
    Java并发编程:volatile关键字解析
    多线程之指令重排序
    《paste命令》-linux命令五分钟系列之二十
    《cut命令》-linux命令五分钟系列之十九
    《ln命令》-linux命令五分钟系列之十八
    Clone Graph
    House Robber
    《wc》-linux命令五分钟系列之十七
    who am i
    《man男人》-linux命令五分钟系列之十五
  • 原文地址:https://www.cnblogs.com/flish/p/2864240.html
Copyright © 2011-2022 走看看