/// <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();
}

  

        /// <summary>
/// GirdView转换成DataTable
/// 20150813
/// 涂聚文
/// </summary>
/// <param name="dgv"></param>
/// <returns></returns>
public static DataTable GetGirdViewToTableHeaderText(DataGridView dgv)
{
DataTable dt = new DataTable();
try
{
for (int count = 0; count < dgv.Columns.Count; count++)
{
if (dgv.Columns[count].Visible == true)
{
DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText);
dt.Columns.Add(dc);
} }
for (int count = 0; count < dgv.Rows.Count; count++)
{
DataRow dr = dt.NewRow();
for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
{
if (dgv.Columns[count].Visible == true)
{
//if (dgv[countsub, count].ValueType == typeof(string))
//{
// dr[countsub] = "'" + dgv.Rows[count].Cells[countsub].Value;
//}
//else
//{
dr[countsub] = dgv.Rows[count].Cells[countsub].Value;
//} } }
dt.Rows.Add(dr); }
}
catch (Exception ex)
{
ex.Message.ToString();
}
return dt;
} /// <summary>
/// List 转DataTable
/// 涂聚文
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ConvertListToDataTable(List<string[]> list)
{
// New table.
DataTable table = new DataTable(); // Get max columns.
int columns = 0;
foreach (var array in list)
{
if (array.Length > columns)
{
columns = array.Length;
}
} // Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
} // Add rows.
foreach (var array in list)
{
table.Rows.Add(array);
} return table;
}

  

        /// <summary>
/// 涂聚文
/// 2015.08.18
/// </summary>
/// <param name="dataGridView"></param>
/// <returns></returns>
public static DataTable DataGridViewToDataTable(DataGridView dataGridView)
{ DataTable dt = new DataTable();
try
{
foreach (DataGridViewColumn col in dataGridView.Columns)
{
if (col.Visible == true)
{
dt.Columns.Add(col.HeaderText, col.ValueType);
}
}
foreach (DataGridViewRow gridRow in dataGridView.Rows)
{
if (gridRow.IsNewRow)
continue;
int irow = 0;
DataRow dtRow = dt.NewRow();
for (int i1 = 0; i1 < dataGridView.Columns.Count; i1++)
{
if (dataGridView.Columns[i1].Visible == true)
{
dtRow[irow] = (gridRow.Cells[i1].Value == null ? DBNull.Value : gridRow.Cells[i1].Value);
irow++;
} }
dt.Rows.Add(dtRow);
}
//ds.Tables.Add(dt);
//System.Diagnostics.Debugger.Break();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
return dt; }
/// <summary>
/// 涂聚文
/// </summary>
/// <param name="dgv"></param>
/// <returns></returns>
public static DataTable GetGirdViewToTableHeaderText(DataGridView dgv)
{ //DataGridViewColumnCollection DataTable dt = new DataTable();
try
{
//标题
for (int count = 0; count < dgv.Columns.Count; count++)
{
if (dgv.Columns[count].Visible == true)
{
DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText, dgv.Columns[count].ValueType);
dt.Columns.Add(dc);
} } for (int count = 0; count < dgv.Rows.Count; count++)
{
int irow = 0;
DataRow dr = dt.NewRow();
//DataRow dr = dt.Rows.Add();
for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
{
if (dgv.Columns[countsub].Visible == true)
{
//if (dgv[countsub, count].ValueType == typeof(string))
//{
// dr[countsub] = "'" + dgv.Rows[count].Cells[countsub].Value;
//}
//elsedt.Rows[countsub][count]
//{
//dr[countsub] = dgv[countsub, count].Value;// dgv.Rows[count].Cells[countsub].Value;
dr[irow] = dgv.Rows[count].Cells[countsub].Value; // dgv[countsub, count].Value;
//} irow++;
} }
dt.Rows.Add(dr); }
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
return dt;
}

  

csharp: Export DataSet into Excel and import all the Excel sheets to DataSet的更多相关文章

  1. csharp: Export or Import excel using MyXls,Spire.Xls

    excel 2003 (效果不太理想) using System; using System.Collections.Generic; using System.ComponentModel; usi ...

  2. ou can mix require and export. You can't mix import and module.exports.

    ou can mix require and export. You can't mix import and module.exports.

  3. ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据

    ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案   ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...

  4. Java POI 导出EXCEL经典实现 Java导出Excel

    转自http://blog.csdn.net/evangel_z/article/details/7332535 在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者 ...

  5. C#实现Excel模板导出和从Excel导入数据

    午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.封装的Exc ...

  6. C# 操作Excel基础篇(读取Excel、写入Excel)

    注意事项:Excel的数据表中最多只能储存65535行数据,超出后,需要将数据分割开来进行储存.同时对于Excel中的乱码象限,是由于编码的错误方式导致引起的! 一.读取Excel数据表,获得Data ...

  7. html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式

    先上代码   <script type="text/javascript" language="javascript">   var idTmr; ...

  8. [从产品角度学EXCEL 00]-为什么要关注EXCEL的本质

    前言 Hello 大家好,我是尾巴,从今天开始,在这里连载<从产品角度学EXCEL>的系列文章.本文不接受无授权转载,如需转载,请先联系我,非常感谢. 与世面上的大部分EXCEL教程不同的 ...

  9. c#.net对excel的操作——创建一个excel报表两个sheet就是2个表分别添加内容

    添加引用:Microsoft.Office.Interop.Excel //创建excel对象,就是实例化一个excel对象            Application excel=new Appl ...

随机推荐

  1. 支持取消操作和暂停操作的Backgroundworker

    这也是今天讨论的话题.取消是默认就支持的,而暂停则默认不支持.但通过ManualResetEvent可以对其进行干预. using System; using System.Collections.G ...

  2. ASP.NET 回调技术(CallBack)

    在asp.net中客户端与服务器端的交互默认都是整页面提交, 此时客户端将当前页面表单中的数据(包括一些自动生成的隐藏域)都提交到服务器端,服务器重新实例化一个当前页面类的实例响应这个请求,然后将整个 ...

  3. [转]BloomFilter——大规模数据处理利器

    Bloom Filter是由Bloom在1970年提出的一种多哈希函数映射的快速查找算法.通常应用在一些需要快速判断某个元素是否属于集合,但是并不严格要求100%正确的场合. 一. 实例 为了说明Bl ...

  4. 再也不必当心我的密码了,多个SAP 客户端自动输入密码

    再也不必当心我的密码了,多个SAP 客户端自动输入密码问题: 通常对于OFFICE人员来说,一天有很多的密码,OA密码,多个ERP密码,邮箱密码,代理密码等等,还经常60天过期之类,实在是焦头烂额. ...

  5. MFC一个类访问另一个类成员对象的成员变量值

    MFC中一个类要访问另外一个类的的对象的成员变量值,这就需要获得原来那个类对象的指针,其实有好几种方法都可以实现. 比如维护一个单例模式.设置静态变量等等.我们这里举个列子,实现多个类之间的相互访问. ...

  6. eclipse 编译出错(java.io.ObjectInputStream)的解决办法

    Multiple markers at this line - The type java.io.ObjectInputStream cannot be resolved. It is indirec ...

  7. Python--Cmd窗口运行Python时提示Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: cp65001

    源地址连接: http://www.tuicool.com/articles/ryuaUze 最近,我在把一个 Python 2 的视频下载工具 youku-lixian 改写成 Python 3,并 ...

  8. vs.net 2005 C# WinForm GroupBOX 的BUG?尝试读取或写入受保护的内存。这通常指示其他内存已损坏

    其实很久没有写程序了,国庆难得有空闲,写了个游戏辅助机器人,程序写好能用后本想把UI控件放到GroupBox里归下分类,美化下界面,结果一运行报“尝试读取或写入受保护的内存.这通常指示其他内存已损坏” ...

  9. Apache MPM winnt

    Win32DisableAcceptEx 指令在 apache2.4 被 AcceptFilter None 取代

  10. new/delete和malloc/free的区别

    通俗易懂版本:http://zhidao.baidu.com/question/86185100 1 new/delete和malloc/free最大区别是对对象的理解. 如果你使用 Foo* foo ...