zoukankan      html  css  js  c++  java
  • Excel操作类

    1.新建Excel并保存数据

    2.追加Excel并自动分页保存数据

    View Code
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Diagnostics;
    using System.IO;
    using System.Collections;
    using System.Data;

    namespace AssismentForm
    {
    /// <summary>
    /// excel操作类
    /// 开发环境:2007
    /// </summary>
    public class ExcelHelper1 : IDisposable
    {
    #region 构造函数
    /// <summary>
    /// 构造函数,打开一个已有的工作簿
    /// </summary>
    /// <param name="fileName">Excel文件名</param>
    public ExcelHelper1(string fileName)
    {
    if (!File.Exists(fileName))
    throw new Exception("指定路径的Excel文件不存在!");
    //创建一个Application对象并使其可见
    excelApp = new Excel.ApplicationClass();

    excelApp.Visible = false;
    excelApp.DisplayAlerts = false;
    excelApp.AlertBeforeOverwriting = false;

    //打开一个WorkBook
    workBook = excelApp.Workbooks.Open(fileName,
    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);

    //得到WorkSheet对象
    workSheet = (Excel.Worksheet)workBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    }

    /// <summary>
    /// 构造函数,新建一个工作簿
    /// </summary>
    public ExcelHelper1()
    {
    excelApp = new Excel.ApplicationClass();
    excelApp.Visible = false;
    //设置禁止弹出保存和覆盖的询问提示框

    excelApp.DisplayAlerts = false;
    excelApp.AlertBeforeOverwriting = false;

    //新建一个WorkBook
    workBook = excelApp.Workbooks.Add(Type.Missing);

    //得到WorkSheet对象
    workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
    ((Excel.Worksheet)workBook.Sheets.get_Item(2)).Delete();
    ((Excel.Worksheet)workBook.Sheets.get_Item(2)).Delete();
    }
    #endregion

    #region 成员变量
    //输出路径
    private string outputFile = null;
    private object missing = System.Reflection.Missing.Value;
    /// <summary>
    /// ExcelApp应用程序
    /// </summary>
    public Excel.Application excelApp;
    Excel.Workbook workBook;
    /// <summary>
    /// 工作表
    /// </summary>
    public Excel.Worksheet workSheet;
    Excel.Range range;
    Excel.Range range1;
    Excel.Range range2;
    Excel.TextBox textBox;
    //WorkSheet数量
    private int sheetCount = 1;
    #endregion

    #region 公共属性
    /// <summary>
    /// 输出Excel文件路径
    /// </summary>
    public string OutputFilePath
    {
    set { this.outputFile = value; }
    }
    #endregion

    #region 公共方法

    #region Data Export Methods

    /// <summary>
    /// 将DataTable数据写入Excel文件(不分页)
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <param name="top">表格数据起始行索引</param>
    /// <param name="left">表格数据起始列索引</param>
    public void DataTableToExcel(DataTable dt, int top, int left)
    {
    int rowCount = dt.Rows.Count; //DataTable行数
    int colCount = dt.Columns.Count; //DataTable列数
    //利用二维数组批量写入
    object[,] arr = new object[rowCount + 1, colCount];
    for (int j = 0; j < rowCount; j++)
    {
    for (int k = 0; k < colCount; k++)
    {
    if (j == 0)
    {
    arr[j, k] = dt.Columns[k].ColumnName;
    }
    arr[j + 1, k] = dt.Rows[j][k].ToString();
    }
    }
    range = (Excel.Range)workSheet.Cells[top, left];
    range = range.get_Resize(rowCount + 1, colCount);
    range.Value2 = arr;
    }

    /// <summary>
    /// 将DataTable数据写入Excel文件(自动分页)
    /// </summary>
    /// <param name="dt">DataTable</param>
    /// <param name="sheetCounts">sheet数量</param>
    /// <param name="top">表格数据起始行索引</param>
    /// <param name="left">表格数据起始列索引</param>
    /// <param name="rowsList">每个sheet行数</param>
    /// <param name="nameList">名字列表</param>
    public void DataTableToExcel(DataTable dt, int sheetCounts, List<int> rowsList, List<string> nameList, int top, int left)
    {
    int rowCount = dt.Rows.Count; //源DataTable行数
    int colCount = dt.Columns.Count; //源DataTable列数
    sheetCount = sheetCounts; //WorkSheet个数

    //复制sheetCount-1个WorkSheet对象
           for (int i = 1; i < sheetCount; i++)
    {
    workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
    workSheet.Copy(missing, workBook.Worksheets[i]);
    }
    int rows = 0;
    for (int i = 1; i <= sheetCount; i++)
    {
    int startRow = rows; //记录起始行索引
    rows += rowsList[i - 1];

    //获取要写入数据的WorkSheet对象,并重命名
    workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
    workSheet.Name = i + "-" + nameList[i - 1];
    //利用二维数组批量写入
    int row = rowsList[i - 1];
    object[,] ss = new object[row + 1, colCount];

    for (int j = 0; j < row; j++)
    {
    for (int k = 0; k < colCount; k++)
    {
    if (j == 0)
    {
    ss[j, k] = dt.Columns[k].ColumnName;
    }
    ss[j + 1, k] = dt.Rows[startRow + j][k].ToString();
    }
    }
    range = (Excel.Range)workSheet.Cells[top, left];
    range = range.get_Resize(row + 1, colCount);
    range.Value2 = ss;
    }
    }
    #endregion

    #region 输出Excel(注意:如果目标文件已存在的话会出错)

    /// <summary>
    /// 保存文件
    /// </summary>
    public void SaveFile()
    {
    try
    {
    workBook.Save();
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    this.Quit();
    }
    }

    /// <summary>
    /// 另存文件
    /// </summary>
    public void SaveAsFile()
    {
    if (this.outputFile == null)
    throw new Exception("没有指定输出文件路径!");

    try
    {
    workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    this.Quit();

    }
    }

    /// <summary>
    /// 将Excel文件另存为指定格式
    /// </summary>
    /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
    public void SaveAsFile(string format)
    {
    if (this.outputFile == null)
    throw new Exception("没有指定输出文件路径!");

    try
    {
    switch (format)
    {
    case "HTML":
    {
    workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    case "CSV":
    {
    workBook.SaveAs(outputFile, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    case "TEXT":
    {
    workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    default:
    {
    workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    }
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    this.Quit();
    }
    }

    /// <summary>
    /// 另存文件
    /// </summary>
    /// <param name="fileName">文件名</param>
    public void SaveFile(string fileName)
    {
    try
    {
    workBook.SaveAs(fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    this.Quit();

    }
    }

    /// <summary>
    /// 将Excel文件另存为指定格式
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
    public void SaveAsFile(string fileName, string format)
    {
    try
    {
    switch (format)
    {
    case "HTML":
    {
    workBook.SaveAs(fileName, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    case "CSV":
    {
    workBook.SaveAs(fileName, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    case "TEXT":
    {
    workBook.SaveAs(fileName, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    default:
    {
    workBook.SaveAs(fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
    break;
    }
    }
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    this.Quit();
    }
    }
    #endregion

    #endregion

    #region 私有方法

    /// <summary>
    /// 结束Excel进程
    /// </summary>
    public void KillExcelProcess(bool bAll)
    {
    if (bAll)
    {
    Process[] myProcesses;
    myProcesses = Process.GetProcessesByName("Excel");

    //得不到Excel进程ID,暂时只能判断进程启动时间
    foreach (Process myProcess in myProcesses)
    {
    myProcess.Kill();
    continue;
    }
    }
    else
    {
    KillSpecialExcel();
    }
    }

    [DllImport("user32.dll", SetLastError = true)]
    static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

    /// <summary>
    /// 结束Excel进程(特殊方式)
    /// </summary>
    public void KillSpecialExcel()
    {
    try
    {
    if (excelApp != null)
    {
    int lpdwProcessId = 0;
    GetWindowThreadProcessId((IntPtr)excelApp.Hwnd, out lpdwProcessId);
    //c-s方式
    if (lpdwProcessId > 0)
    {
    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
    }
    else
    {
    Quit();
    }
    }
    }
    catch { }
    }

    /// <summary>
    /// 退出
    /// </summary>
    public void Quit()
    {
    if (workBook != null)
    workBook.Close(null, null, null);
    if (excelApp != null)
    {
    excelApp.Workbooks.Close();
    excelApp.Quit();
    }

    if (range != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    range = null;
    }
    if (range1 != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range1);
    range1 = null;
    }
    if (range2 != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range2);
    range2 = null;
    }
    if (textBox != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(textBox);
    textBox = null;
    }
    if (workSheet != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
    workSheet = null;
    }
    if (workBook != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);

    workBook = null;
    }
    if (excelApp != null)
    {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
    excelApp = null;
    }
    GC.Collect();
    }//end Quit
    #endregion
    }
    }
  • 相关阅读:
    基于Metaweblog API 接口一键发布到国内外主流博客平台
    uva144 Student Grants
    Uva 10452
    Uva 439 Knight Moves
    Uva 352 The Seasonal War
    switch语句
    java——基础知识
    我的lua学习2
    codeforces 431 D. Random Task 组合数学
    codeforces 285 D. Permutation Sum 状压 dfs打表
  • 原文地址:https://www.cnblogs.com/ghypnus/p/2412417.html
Copyright © 2011-2022 走看看