如何选择多个表以导出到excel [英] how to select more than one table for export to excel

查看:82
本文介绍了如何选择多个表以导出到excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我在gridview中显示了所有的表名.我想通过单击复选框从该gridview表中导出多个表...请帮助我

In my program i displayed all the table names with in the gridview.I want export more than one table from that gridview tables by clicking on the checkbox... pls help me

推荐答案

基本上,您必须创建一个excel对象,并填充每个工作表(代表表格的工作表)的单元格.这是类似的内容:
You basically have to create an excel object, and fill the cells of each sheet (a sheet representing a table). Here is something similar:
private static void Excel(string fileName, List<IDirectoryInventoryDataCollector> list)
{
    try
    {
        var xlApp = new Excel.Application();
        var xlWorkBook = xlApp.Workbooks.Add();
        var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        ExcelTitleRow(list[0], 1, xlWorkSheet);

        int row = 2;
        foreach (var item in list)
        {
            ExcelFillRow(item, row++, xlWorkSheet);
        }

        for (int i = 1; i < list[0].MaxLevel - 1; i++)
        {
            ((Range)xlWorkSheet.Columns[i]).ColumnWidth = 2;
        }
        ((Range)xlWorkSheet.Columns[list[0].MaxLevel - 1]).ColumnWidth = 30;
        ((Range)xlWorkSheet.Rows[1]).WrapText = true;
        ((Range)xlWorkSheet.Rows[1]).HorizontalAlignment = HorizontalAlignment.Center;
        ((Range)xlWorkSheet.Cells[1, 1]).WrapText = false;

        xlWorkBook.SaveAs(fileName);
        xlWorkBook.Close();
        xlApp.Quit();
    }
    catch (AccessViolationException)
    {
        System.Windows.Forms.MessageBox.Show(
             "Have encountered access violation. This could be issue with Excel 2000 if that is only version installed on computer",
             "Access Violation");
    }
    catch (Exception)
    {
        System.Windows.Forms.MessageBox.Show("Unknown error",
             "Unknown error");
    }
}

private static void ExcelFillRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
    sheet.Cells[row, item.Level] = item.Name;
    int column = item.MaxLevel;
    foreach (var property in item.GetProperties())
    {
        sheet.Cells[row, column++] = property;
    }
}

private static void ExcelTitleRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
    sheet.Cells[row, 1] = "Name";
    int column = item.MaxLevel;
    foreach (var property in item.GetPropertyNames())
    {
        sheet.Cells[row, column++] = property;
    }
}


这篇关于如何选择多个表以导出到excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆