C# Excel 操作
Excel数据到datagridview 里面 (流读取)
System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog(); if (fd.ShowDialog() == DialogResult.OK)
{
DataTable DT = Table(fd.FileName); int CellCount = DT.Columns.Count;
int RowCount = DT.Rows.Count;
List<string> list = new List<string>();
for (int a = ; a <= CellCount - ; a++)
{
list.Add(DT.Rows[][a].ToString());
}
dataGridViewX1.DataSource = DT;
DT.Rows.RemoveAt(); for (int b = ; b < CellCount; b++)
{ dataGridViewX1.Columns[b].HeaderCell.Value = list[b];
dataGridViewX1.Columns[b].Name = list[b]; }
DevComponents.DotNetBar.Controls.DataGridViewX Da = new DevComponents.DotNetBar.Controls.DataGridViewX(); }
public DataTable Table(string ST)
{
// string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ST + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ST + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$] ";
myConn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn); DataSet myDataSet = new DataSet(); myCommand.Fill(myDataSet, "[Sheet1$]"); myConn.Close();
return myDataSet.Tables[]; }
C# datagridview 数据到Excel 流导出
DataTable DT = new DataTable();
DataRow DR = DT.NewRow();
for(int a = ;a<dataGridViewX1.Columns.Count;a++)
{
DT.Columns.Add(dataGridViewX1.Columns[a].HeaderCell.Value.ToString(),Type.GetType("System.String"));
}
int RowCount = dataGridViewX1.Rows.Count;
int CellCount = dataGridViewX1.Columns.Count;
for (int a = ; a < RowCount-; a++)
{//新实例化数据
DR = DT.NewRow(); for (int b = ; b < CellCount; b++)
{
// dataRow 构建行数据 构建一条添加一条
DR[b] = dataGridViewX1.Rows[a].Cells[b].Value.ToString();
}
DT.Rows.Add(DR); }
//dataGridViewX1.Rows.Clear(); DataGridViewExportToExcel(DT, "导出Excel");
}
public void DataGridViewExportToExcel(DataTable Tab, string strTitle)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = ;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = false;
saveFileDialog.FileName = strTitle + ".xls";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel) //导出时,点击【取消】按钮
{
return;
}
Stream myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream,System.Text.Encoding.GetEncoding(-));
string strHeaderText = "";
try
{
//写标题
for (int i = ; i < Tab.Columns.Count; i++)
{
if (i > )
{
strHeaderText += "\t";
}
strHeaderText += Tab.Columns[i].ToString();
}
sw.WriteLine(strHeaderText);
//写内容
string strItemValue = "";
for (int j = ; j < Tab.Rows.Count; j++)
{
strItemValue = "";
for (int k = ; k < Tab.Columns.Count; k++)
{
if (k > )
{
strItemValue += "\t";
}
strItemValue += Tab.Rows[j][k].ToString();
}
sw.WriteLine(strItemValue); //把dgv的每一行的信息写为sw的每一行
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "软件提示");
throw ex;
}
finally
{
sw.Close();
myStream.Close();
}
}
导出Excel (worksheet)
public void Exportdatagridviewtoexcel(DataGridView mydgv)
{
if (mydgv.Rows.Count == )
{
MessageBox.Show(" 没有数据可供导出!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
SaveFileDialog savedialog = new SaveFileDialog();
savedialog.DefaultExt = "xlsx";
savedialog.Filter = "microsoft office execl files (*.xlsx)|*.xlsx";
savedialog.FilterIndex = ;
savedialog.RestoreDirectory = true;
savedialog.Title = "导出数据到excel表格";
savedialog.ShowDialog();
if (savedialog.FileName.IndexOf(":") < ) return; //被点了取消
//Microsoft.office.interop.excel.application xlapp = new microsoft.office.interop.excel.application();
Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
if (xlapp == null)
{
MessageBox.Show("可能您的机子未安装excel,无法创建excel对象!", "系统提示 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
} 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[];//取得sheet1
//定义表格内数据的行数和列数
int rowscount = mydgv.Rows.Count;
int colscount = mydgv.Columns.Count;
//行数不可以大于65536
if (rowscount > )
{
MessageBox.Show("数据行记录超过65536行,不能保存!", "系统提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//列数不可以大于255
if (colscount > )
{
MessageBox.Show("数据列记录超过256列,不能保存!", "系统提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//写入大标题
string text = US_GV.UserDeptName + "—库存初始化报表"; worksheet.get_Range(worksheet.Cells[, ], worksheet.Cells[, ]).MergeCells = true;
worksheet.get_Range(worksheet.Cells[, ], worksheet.Cells[, ]).Font.Size = ;
worksheet.get_Range(worksheet.Cells[, ], worksheet.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
worksheet.get_Range(worksheet.Cells[, ], worksheet.Cells[, ]).Font.Bold = true; worksheet.Cells[, ] = text;
//写入列名
for (int i = ; i < mydgv.ColumnCount; i++)
{
worksheet.Cells[, i + ] = mydgv.Columns[i].HeaderText;
}
//写入数值
for (int r = ; r < mydgv.Rows.Count; r++)
{
for (int i = ; i < mydgv.ColumnCount; i++)
{
if (mydgv[i, r].ValueType == typeof(string))
{ worksheet.Cells[r + , i + ] = "" + mydgv.Rows[r].Cells[i].Value.ToString().Replace(" ", ""); ;//将长数值转换成文本
}
else
{
worksheet.Cells[r + , i + ] = mydgv.Rows[r].Cells[i].Value.ToString().Replace(" ", ""); ;
}
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
if (savedialog.FileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(savedialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show("导出文件时出错,文件可能正被打开!..." + ex.Message, "系统提示 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
//GC.Collect();//强行销毁
MessageBox.Show("数据导出成功! ", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); }
}
导出Excel 属性设置 /// <summary>
/// 单元格背景色及填充方式
/// </summary>
/// <param name="startRow">起始行</param>
/// <param name="startColumn">起始列</param>
/// <param name="endRow">结束行</param>
/// <param name="endColumn">结束列</param>
/// <param name="color">颜色索引</param>
public void CellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color)
{
Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]);
range.Interior.ColorIndex = color;
range.Interior.Pattern = Pattern.Solid;
} /// <summary>
/// 单元格背景色及填充方式
/// </summary>
/// <param name="startRow">起始行</param>
/// <param name="startColumn">起始列</param>
/// <param name="endRow">结束行</param>
/// <param name="endColumn">结束列</param>
/// <param name="color">颜色索引</param>
/// <param name="pattern">填充方式</param>
public void CellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color, Pattern pattern)
{
Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]);
range.Interior.ColorIndex = color;
range.Interior.Pattern = pattern;
} /// <summary>
/// 设置行高
/// </summary>
/// <param name="startRow">起始行</param>
/// <param name="endRow">结束行</param>
/// <param name="height">行高</param>
public void SetRowHeight(int startRow, int endRow, int height)
{
//获取当前正在使用的工作表
Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
Excel.Range range = (Excel.Range)worksheet.Rows[startRow.ToString() + ":" + endRow.ToString(), System.Type.Missing];
range.RowHeight = height;
} /// <summary>
/// 自动调整行高
/// </summary>
/// <param name="columnNum">列号</param>
public void RowAutoFit(int rowNum)
{
//获取当前正在使用的工作表
Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
Excel.Range range = (Excel.Range)worksheet.Rows[rowNum.ToString() + ":" + rowNum.ToString(), System.Type.Missing];
range.EntireColumn.AutoFit(); } /// <summary>
/// 设置列宽
/// </summary>
/// <param name="startColumn">起始列(列对应的字母)</param>
/// <param name="endColumn">结束列(列对应的字母)</param>
/// <param name="width"></param>
public void SetColumnWidth(string startColumn, string endColumn, int width)
{
//获取当前正在使用的工作表
Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
Excel.Range range = (Excel.Range)worksheet.Columns[startColumn + ":" + endColumn, System.Type.Missing];
range.ColumnWidth = width;
} /// <summary>
/// 设置列宽
/// </summary>
/// <param name="startColumn">起始列</param>
/// <param name="endColumn">结束列</param>
/// <param name="width"></param>
public void SetColumnWidth(int startColumn, int endColumn, int width)
{
string strStartColumn = GetColumnName(startColumn);
string strEndColumn = GetColumnName(endColumn);
//获取当前正在使用的工作表
Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
Excel.Range range = (Excel.Range)worksheet.Columns[strStartColumn + ":" + strEndColumn, System.Type.Missing];
range.ColumnWidth = width;
} /// <summary>
/// 自动调整列宽
/// </summary>
/// <param name="columnNum">列号</param>
public void ColumnAutoFit(string column)
{
//获取当前正在使用的工作表
Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
Excel.Range range = (Excel.Range)worksheet.Columns[column + ":" + column, System.Type.Missing];
range.EntireColumn.AutoFit(); } /// <summary>
/// 自动调整列宽
/// </summary>
/// <param name="columnNum">列号</param>
public void ColumnAutoFit(int columnNum)
{
string strcolumnNum = GetColumnName(columnNum);
//获取当前正在使用的工作表
Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
Excel.Range range = (Excel.Range)worksheet.Columns[strcolumnNum + ":" + strcolumnNum, System.Type.Missing];
range.EntireColumn.AutoFit(); } /// <summary>
/// 字体颜色
/// </summary>
/// <param name="startRow">起始行</param>
/// <param name="startColumn">起始列</param>
/// <param name="endRow">结束行</param>
/// <param name="endColumn">结束列</param>
/// <param name="color">颜色索引</param>
public void FontColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color)
{
Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]);
range.Font.ColorIndex = color;
} /// <summary>
/// 字体样式(加粗,斜体,下划线)
/// </summary>
/// <param name="startRow">起始行</param>
/// <param name="startColumn">起始列</param>
/// <param name="endRow">结束行</param>
/// <param name="endColumn">结束列</param>
/// <param name="isBold">是否加粗</param>
/// <param name="isItalic">是否斜体</param>
/// <param name="underline">下划线类型</param>
public void FontStyle(int startRow, int startColumn, int endRow, int endColumn, bool isBold, bool isItalic, UnderlineStyle underline)
{
Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]);
range.Font.Bold = isBold;
range.Font.Underline = underline;
range.Font.Italic = isItalic;
} /// <summary>
/// 单元格字体及大小
/// </summary>
/// <param name="startRow">起始行</param>
/// <param name="startColumn">起始列</param>
/// <param name="endRow">结束行</param>
/// <param name="endColumn">结束列</param>
/// <param name="fontName">字体名称</param>
/// <param name="fontSize">字体大小</param>
public void FontNameSize(int startRow, int startColumn, int endRow, int endColumn,string fontName, int fontSize)
{
Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]);
range.Font.Name = fontName;
range.Font.Size = fontSize;
} /// <summary>
/// 打开一个存在的Excel文件
/// </summary>
/// <param name="fileName">Excel完整路径加文件名</param>
public void Open(string fileName)
{
myExcel = new Excel.Application();
myWorkBook = myExcel.Workbooks.Add(fileName);
myFileName = fileName;
} /// <summary>
/// 保存Excel
/// </summary>
/// <returns>保存成功返回True</returns>
public bool Save()
{
if (myFileName == "")
{
return false;
}
else
{
try
{
myWorkBook.Save();
return true;
}
catch (Exception ex)
{
return false;
}
}
} /// <summary>
/// Excel文档另存为
/// </summary>
/// <param name="fileName">保存完整路径加文件名</param>
/// <returns>保存成功返回True</returns>
public bool SaveAs(string fileName)
{
try
{
myWorkBook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
return true; }
catch (Exception ex)
{
return false; }
} /// <summary>
/// 关闭Excel
/// </summary>
public void Close()
{
myWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
myExcel.Quit();
myWorkBook = null;
myExcel = null;
GC.Collect();
} /// <summary>
/// 关闭Excel
/// </summary>
/// <param name="isSave">是否保存</param>
public void Close(bool isSave)
{
myWorkBook.Close(isSave, Type.Missing, Type.Missing);
myExcel.Quit();
myWorkBook = null;
myExcel = null;
GC.Collect();
} /// <summary>
/// 关闭Excel
/// </summary>
/// <param name="isSave">是否保存</param>
/// <param name="fileName">存储文件名</param>
public void Close(bool isSave,string fileName)
{
myWorkBook.Close(isSave, fileName, Type.Missing);
myExcel.Quit();
myWorkBook = null;
myExcel = null;
GC.Collect();
} #region 私有成员
private string GetColumnName(int number)
{
int h, l;
h = number / ;
l = number % ;
if (l == )
{
h -= ;
l = ;
}
string s = GetLetter(h) + GetLetter(l);
return s;
} private string GetLetter(int number)
{
switch (number)
{
case :
return "A";
case :
return "B";
case :
return "C";
case :
return "D";
case :
return "E";
case :
return "F";
case :
return "G";
case :
return "H";
case :
return "I";
case :
return "J";
case :
return "K";
case :
return "L";
case :
return "M";
case :
return "N";
case :
return "O";
case :
return "P";
case :
return "Q";
case :
return "R";
case :
return "S";
case :
return "T";
case :
return "U";
case :
return "V";
case :
return "W";
case :
return "X";
case :
return "Y";
case :
return "Z";
default:
return "";
}
}
#endregion } /// <summary>
/// 水平对齐方式
/// </summary>
public enum ExcelHAlign
{
常规 = ,
靠左,
居中,
靠右,
填充,
两端对齐,
跨列居中,
分散对齐
} /// <summary>
/// 垂直对齐方式
/// </summary>
public enum ExcelVAlign
{
靠上 = ,
居中,
靠下,
两端对齐,
分散对齐
} /// <summary>
/// 线粗
/// </summary>
public enum BorderWeight
{
极细 = ,
细 = ,
粗 = -,
极粗 =
} /// <summary>
/// 线样式
/// </summary>
public enum LineStyle
{
连续直线 = ,
短线 = -,
线点相间 = ,
短线间两点 = ,
点 = -,
双线 = -,
无 = -,
少量倾斜点 =
} /// <summary>
/// 下划线方式
/// </summary>
public enum UnderlineStyle
{
无下划线 = -,
双线 = - ,
双线充满全格 = ,
单线 = ,
单线充满全格 =
} /// <summary>
/// 单元格填充方式
/// </summary>
public enum Pattern
{
Automatic = -,
Checker = ,
CrissCross = ,
Down = -,
Gray16 = ,
Gray25 = -,
Gray50 = -,
Gray75 = -,
Gray8 = ,
Grid = ,
Horizontal = -,
LightDown = ,
LightHorizontal = ,
LightUp = ,
LightVertical = ,
None = -,
SemiGray75 = ,
Solid = ,
Up = -,
Vertical = -
} /// <summary>
/// 常用颜色定义,对就Excel中颜色名
/// </summary>
public enum ColorIndex
{
无色 = -,
自动 = -,
黑色 = ,
褐色 = ,
橄榄 = ,
深绿 = ,
深青 = ,
深蓝 = ,
靛蓝 = ,
灰色80 = ,
深红 = ,
橙色 = ,
深黄 = ,
绿色 = ,
青色 = ,
蓝色 = ,
蓝灰 = ,
灰色50 = ,
红色 = ,
浅橙色 = ,
酸橙色 = ,
海绿 = ,
水绿色 = ,
浅蓝 = ,
紫罗兰 = ,
灰色40 = ,
粉红 = ,
金色 = ,
黄色 = ,
鲜绿 = ,
青绿 = ,
天蓝 = ,
梅红 = ,
灰色25 = ,
玫瑰红 = ,
茶色 = ,
浅黄 = ,
浅绿 = ,
浅青绿 = ,
淡蓝 = ,
淡紫 = ,
白色 =
}
}
C# Excel 操作的更多相关文章
- Npoi导入导出Excel操作
之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...
- Delphi Excel 操作大全
Delphi Excel 操作大全 (一) 使用动态创建的方法首先创建 Excel 对象,使用ComObj:var ExcelApp: Variant;ExcelApp := CreateOleObj ...
- C#EXCEL 操作类--C#ExcelHelper操作类
主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...
- Excel 操作类
转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...
- C# excel操作
开源的Excel操作项目: http://www.cnblogs.com/lwme/archive/2011/11/27/2265323.html 添加引用:Microsoft Excel 11.0 ...
- [Excel操作]Microsoft Office Excel 不能访问文件
最近,客户服务器迁移,因操作系统环境变化而引起的的环境问题一堆,遇到的问题并解决方法在“[Excel]操作”类别会体现. Microsoft Office Excel 不能访问文件“C:\\LMSEx ...
- C#常用工具类——Excel操作类
/// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...
- 报表中的Excel操作之Aspose.Cells(Excel模板)
原文:报表中的Excel操作之Aspose.Cells(Excel模板) 本篇中将简单记录下Aspose.Cells这个强大的Excel操作组件.这个组件的强大之处,就不多说,对于我们的报表总是会有导 ...
- C# Excel操作类
/// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...
- Excel操作 Microsoft.Office.Interop.Excel.dll的使用
----转载: http://www.cnblogs.com/lanjun/archive/2012/06/17/2552920.html 先说说题外话,前段时间近一个月,我一直在做单据导入功能,其中 ...
随机推荐
- go语言学习杂记
go语言在windows下下载安装 推荐在golang中国下载 http://www.golangtc.com/download 安装.... go环境变量与工作目录 根据约定GOPATH需要建立3个 ...
- Oracle linux 6.3 安装11g R2 RAC on vbox
1 安装系统 Virtual box 4.3 Oracle linux 6.3 Oracle 11g r2 Make sure "Adapter 1" is enabled, se ...
- mongoDB的了解
一.什么是mongoDB? 1.MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统.在高负载的情况下,添加更多的节点,可以保证服务器性能. 2.MongoDB 旨在为WEB ...
- MVC原理图解
注解: 视图中通过Action方法向控制器请求数据 控制器通过view()方法向视图呈现数据
- 软件部需求,内容采集,显示内容图文列表,MongoDB数据导入导出JSON
全局变量 由于多个html页面,需要引用同一个变量.这个时候,需要定义一个全局变量!如何定义呢? 默认包含了mui的html文件都导入mui.js文件.那么将变量写在mui.js中,就可以实现所有页面 ...
- csdn知识库
- C#操作SQLIte数据。
using System; using System.Data; using System.Text.RegularExpressions; using System.Xml; using Syste ...
- Scala中的函数
Scala中的函数 提纲 1.Scala中的函数简介 2.Scala中的函数的各种写法 1.Scala中的函数简介 =================== Scala是函数式编程和面向对象式编程的混合 ...
- Collection Types
[Collection Types] 1.Arrays store ordered lists of values of the same type. Value必须是同一类型. 2.Array的原型 ...
- 浅谈块元素绝对定位的margin属性
对于div的绝对定位一直以为margin属性是无效的,只是通过top,left,bottom,right定位,然而今天的却发现不是这样的,于是对其做了些实验: 使用的HTML原始测试文件: <! ...