csharp: Export DataSet into Excel and import all the Excel sheets to DataSet

简介: /// <summary> /// Export DataSet into Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> pri
/// <summary>
       /// Export DataSet into Excel
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       private void Form3_Load(object sender, EventArgs e)
       {
           //Create an Emplyee DataTable
           DataTable employeeTable = new DataTable("Employee");
           employeeTable.Columns.Add("Employee ID");
           employeeTable.Columns.Add("Employee Name");
           employeeTable.Rows.Add("1", "涂聚文");
           employeeTable.Rows.Add("2", "geovindu");
           employeeTable.Rows.Add("3", "李蘢怡");
           employeeTable.Rows.Add("4", "ноппчц");
           employeeTable.Rows.Add("5", "ニヌネハヒフキカォноппчц");
           //Create a Department Table
           DataTable departmentTable = new DataTable("Department");
           departmentTable.Columns.Add("Department ID");
           departmentTable.Columns.Add("Department Name");
           departmentTable.Rows.Add("1", "IT");
           departmentTable.Rows.Add("2", "HR");
           departmentTable.Rows.Add("3", "Finance");
 
           //Create a DataSet with the existing DataTables
           DataSet ds = new DataSet("Organization");
           ds.Tables.Add(employeeTable);
           ds.Tables.Add(departmentTable);
 
           ExportDataSetToExcel(ds);
       }
 
       /// <summary>
       /// This method takes DataSet as input paramenter and it exports the same to excel
       /// </summary>
       /// <param name="ds"></param>
       private void ExportDataSetToExcel(DataSet ds)
       {
           //Creae an Excel application instance
           //EXCEL组件接口
           System.Reflection.Missing miss = System.Reflection.Missing.Value;
           Excel.Application excelApp = new Excel.Application();
           excelApp.Application.Workbooks.Add(true);
           string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
           string FilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "geovindu" + timeMark + ".xlsx");
           //Create an Excel workbook instance and open it from the predefined location
           //Excel.Workbook excelWorkBook = excelApp.Workbooks.Open(FilePath);
           Excel.Workbooks books = (Excel.Workbooks)excelApp.Workbooks;
           Excel.Workbook excelWorkBook = (Excel.Workbook)books.Add(miss);
           foreach (DataTable table in ds.Tables)
           {
               //Add a new worksheet to workbook with the Datatable name
               Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
               excelWorkSheet.Name = table.TableName;
 
               for (int i = 1; i < table.Columns.Count + 1; i++)
               {
                   excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
               }
 
               for (int j = 0; j < table.Rows.Count; j++)
               {
                   for (int k = 0; k < table.Columns.Count; k++)
                   {
                       excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
                   }
               }
           }
 
           excelWorkBook.SaveAs(FilePath, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, System.Text.Encoding.UTF8, miss, miss);
           excelWorkBook.Close(false, miss, miss);
           //excelWorkBook.Save();
           books.Close();
           excelApp.Quit();
 
       }


/// <summary>
       /// EXCEL表的所有工作表导入到DataSet
       /// 涂聚文 Microsoft.ACE.OLEDB.12.0
       /// Geovin Du
       /// </summary>
       /// <param name="fileName"></param>
       /// <returns></returns>
       static DataSet  ImportExcelParse(string fileName)
       {
           string connectionString = string.Format("provider=Microsoft.Jet.OLEDB.4.0; data source={0};Extended Properties=Excel 8.0;", fileName);
 
 
           DataSet data = new DataSet();
 
           foreach (var sheetName in GetExcelSheetNames(connectionString))
           {
               using (OleDbConnection con = new OleDbConnection(connectionString))
               {
                   var dataTable = new DataTable();
                   string query = string.Format("SELECT * FROM [{0}]", sheetName);
                   con.Open();
                   OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
                   adapter.Fill(dataTable);
                   data.Tables.Add(dataTable);
               }
           }
 
           return data;
       }
       /// <summary>
       /// 读取所有工作表名
       /// </summary>
       /// <param name="connectionString"></param>
       /// <returns></returns>
       static string[] GetExcelSheetNames(string connectionString)
       {
           OleDbConnection con = null;
           DataTable dt = null;
           con = new OleDbConnection(connectionString);
           con.Open();
           dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
 
           if (dt == null)
           {
               return null;
           }
 
           String[] excelSheetNames = new String[dt.Rows.Count];
           int i = 0;
 
           foreach (DataRow row in dt.Rows)
           {
               excelSheetNames[i] = row["TABLE_NAME"].ToString();
               i++;
           }
 
           return excelSheetNames;
       }

/// <summary>
       /// 添加图片
       /// 涂聚文
       /// </summary>
       /// <param name="dt"></param>
       protected void ExportExcelImg(System.Data.DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0) return;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();   
            if (xlApp == null)
            {
                return;
            }
            xlApp.Application.Workbooks.Add(true);
            string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
            string FilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "geovindu" + timeMark + ".xlsx");
 
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
 
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            Microsoft.Office.Interop.Excel.Range range;
            System.Reflection.Missing miss = System.Reflection.Missing.Value;
            long totalCount = dt.Rows.Count;
            long rowRead = 0;
            float percent = 0;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
                range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
                range.Interior.ColorIndex = 15;
            }
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    try
                    {
                        worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
                    }
                    catch
                    {
                        worksheet.Cells[r + 2, i + 1] =
               dt.Rows[r][i].ToString().Replace("=", "");
                    }
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
            }
            string strimg =Application.StartupPath+@"/IMG_6851.JPG";
            worksheet.Shapes.AddPicture(strimg, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300);
           //在添加的图片上加文字
            worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "涂聚文写上", "Red", 15, Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200);
            xlApp.Visible = true;
 
            workbook.SaveAs(FilePath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, System.Text.Encoding.UTF8, miss, miss);
            workbook.Close(false, miss, miss);
            //excelWorkBook.Save();
            workbooks.Close();
            xlApp.Quit();
        }


目录
相关文章
VS2005(excel2007)利用Automation(OLD Automation)方法。将Excel当成组件服务器的编译错误 我的系统盘和office都装在d盘。 自动生成的import有问题
VS2005(excel2007)利用Automation(OLD Automation)方法。将Excel当成组件服务器的编译错误 我的系统盘和office都装在d盘。 自动生成的import有问题
|
算法
Excel与Google Sheets中实现线性规划求解
本文以非IT开发人员的解决介绍目前市场上最流行的两个规划工具,分别是Microsoft Excel中的【规划求解】组件,和Google Spreadsheet上的Linear Optimization.为普通用户在自己的业务场景中遇到需要通过规划运筹才能解决的问题时,提供科入门参考。
3297 0
|
C#
csharp: Export or Import excel using MyXls
 excel 2003 (效果不太理想) using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System
1530 0
|
C#
csharp: read excel using Aspose.Cells
/// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="strFileName"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Syste
1604 0
Form_Form Builder Export导出为Excel(案例)
2014-01-09 Created By BaoXinjian  一、摘要 以下是关于解决EBS标准导出功能无法导出主从关系数据的方法。 解决思路: 1. 在form上增加一个导出按钮,或者在工具栏注册一个菜单项。
1224 0
|
XML C# 开发工具
csharp: word or excel Convert to PDF
using Word = Microsoft.Office.Interop.Word; //12.0 word 2007 using Excel = Microsoft.Office.Interop.Excel;//12.0 excel 2007 /// &lt;summary&gt; /// EXCEL文檔轉成PDF文檔 /// 參考 h
1331 0
|
C#
csharp read excel file get sheetName list
/// &lt;summary&gt; /// /// 塗聚文 /// 20120803 /// Geovin Du ///找到EXCEL的工作表名称 要考慮打開的文件的進程問題 /// &lt;/summary&gt; /// &lt;p
1121 0
|
1月前
|
数据采集 数据可视化 数据挖掘
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####