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 操作的更多相关文章

  1. Npoi导入导出Excel操作

    之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...

  2. Delphi Excel 操作大全

    Delphi Excel 操作大全 (一) 使用动态创建的方法首先创建 Excel 对象,使用ComObj:var ExcelApp: Variant;ExcelApp := CreateOleObj ...

  3. C#EXCEL 操作类--C#ExcelHelper操作类

    主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...

  4. Excel 操作类

    转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...

  5. C# excel操作

    开源的Excel操作项目: http://www.cnblogs.com/lwme/archive/2011/11/27/2265323.html 添加引用:Microsoft Excel 11.0 ...

  6. [Excel操作]Microsoft Office Excel 不能访问文件

    最近,客户服务器迁移,因操作系统环境变化而引起的的环境问题一堆,遇到的问题并解决方法在“[Excel]操作”类别会体现. Microsoft Office Excel 不能访问文件“C:\\LMSEx ...

  7. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  8. 报表中的Excel操作之Aspose.Cells(Excel模板)

    原文:报表中的Excel操作之Aspose.Cells(Excel模板) 本篇中将简单记录下Aspose.Cells这个强大的Excel操作组件.这个组件的强大之处,就不多说,对于我们的报表总是会有导 ...

  9. C# Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  10. Excel操作 Microsoft.Office.Interop.Excel.dll的使用

    ----转载: http://www.cnblogs.com/lanjun/archive/2012/06/17/2552920.html 先说说题外话,前段时间近一个月,我一直在做单据导入功能,其中 ...

随机推荐

  1. cvc-complex-type.2.4.a: Invalid content was found starting with element 'async-supported'

    <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springfr ...

  2. ffmpeg综合应用示例(一)——摄像头直播

    本文的示例将实现:读取PC摄像头视频数据并以RTMP协议发送为直播流.示例包含了 1.ffmpeg的libavdevice的使用 2.视频解码.编码.推流的基本流程 具有较强的综合性. 要使用liba ...

  3. TELNET协议规范

    ARPA Internet上的主机被要求采用并实现此标准. 介绍 TELNET Protocol的目的是提供一个相对通用的,双向的,面向八位字节的通信方法.它主要的目标是允许接口终端设备的标准方法和面 ...

  4. Java-Maven-Runoob:Maven POM

    ylbtech-Java-Maven-Runoob:Maven POM 1.返回顶部 1. Maven POM POM( Project Object Model,项目对象模型 ) 是 Maven 工 ...

  5. mysql replication /mysql 主从复制原理

    一下内容均是根据leader的培训分享整理而成 ************************************我是分割线*********************************** ...

  6. MFC学习(五)常见面试题

    1:应用程序类 CTestOneApp::InitInstance 可以看做是MFC程序的入口函数,main函数隐藏在这个函数中.实际开发中一般不需要对这个类进行操作,但如果要在建立主对话框之前处理一 ...

  7. mybatis generator 用法

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  8. get与post两种方式的优缺点

    get: get是从服务器上获取数据,post是向服务器传送数据: get传送的数据量较小,不能大于2KB.post传送的数据量较大,一般被默认为不受限制.但理论上,IIS4中最大量为80KB,IIS ...

  9. RabbitMQ操作方法

    /// <summary> /// 消费者(消息) /// </summary> public class CustmerMq { /// <summary> // ...

  10. Tarjan的LCA离线算法

    LCA(Least Common Ancestors)是指树结构中两个结点的最低的公共祖先.而LCA算法则是用于求两个结点的LCA.当只需要求一对结点的LCA时,我们很容易可以利用递归算法在O(n)的 ...