学习目标:
提示:这里可以添加学习目标
例如:
- 一周掌握 Java 入门知识
学习内容:
提示:这里可以添加要学的内容
例如:
- 掌握C#开发基本环境的搭配以及插件的使用。
- 掌握C#Winform 使用NPOI导入、导出Excel
- 掌握条件语句
- 掌握循环语句
代码如下:
`public static void ExportDataToExcel(DataTable TableName){
string FileName= DateTime.Now.GetHashCode().ToString();
SaveFileDialog saveFileDialg=new SaveFileDialog();
//设置文件标题
saveFileDialog.Title ="导出Excel 工作薄(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(`*.xls)|*.xls";
//设置默认文件类型显示顺序
saveFileDialog.FilterInder =1;
//是否自动在文件名中添加扩展名
saveFileDialog.AddExtension =true;
//是否记忆上次打开的目录
saveFileDialog.RestoreDirectory=true;
//设置默认的文件名
saveFileDialog.FileName=FIleName;
//按下确认选择的按钮
if(saveFileDialog.ShowDialog()==DialogResult.OK
{
//获得文件路径
string localFilePath =saveFileDialog.FileName.ToSting();
//数据初始化
int TotalCount; //总行数
int RowRead=0; //已读行数
int Percent=0; //百分比
TotalCount=TableName.Row.Count;
DataTable dt=paramSet.GetDatable(strBaseName);
TotalCount=dt.Rows.Count;
//NPOI
IWorkbook workbook;
string FileExt =Path.GetExtension(localFilePath).ToLower();
if(FileExt==".xlsx"){
workbook=new XSSFWorkbook();}
else if(FileExt==".xls"){
workbook =new HSSFWorkbook();
}else{
workbook=null;
}
if(workbook==null){
return"没有工作簿";
}
}else{
return"导出路径出错";
}
ISheet sheet=string.IsNullorEmpty(FileName)?workbook.CreateSheet("sheet1"):workbook.CreateSheet(FileName);
//秒钟
Stopwatch timer= new Stopwatch();
timer.Start();
try{
//读取标题
for(int i=0;i<dt.Columns.Count;i++){
IRow rowHeader=sheet.CreateRow(i);
ICell cell=rowHeader.CreateCell(0);
cell.SetCellvalue(dt.Colums[i].ColumnName);
}
int cellsit=1;
foreach(DataRow item in dt.Rows){
for(int i=0;i<dt.Columns.Count;i++){
IRow rowData =sheet.GetRow(i);
ICell cell=rowData.Creeatell(cellsit);
cell.SetCellValue(item[i].ToSring());}
cellsit++;
RowRead++;
Percent=(int)
(100*RowRead/TotalCount);
Application.DoEvents();
}
Application.DoEvents();
//转为字节数组
MemoryStream stream=new MemorySteam();
workbook.Write(stream);
var buf =stream.ToArray();
//保存为EXCel文件
using(FileStream fs=new FileStream(localFilePath,FileMode.Create,FileAccess.Write)){
fs.Write(buf,0,buf.Length);
fs.Flush();
fs.Close();}
Application.DoEvents();
//关闭秒表
timer.Reset();
timer.Stop();
//成功提示
if(MessageBox.Show("导出成功,是否立即打开?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.InFormation)==DialogResult.Yes){
System.Diagnostics.Process.Start(localFilePath);}
}
catch(Exception ex){
MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}finally{
timer.Reset();
timer.Stop();
}
}
}
学习产出:
提示:这里统计学习计划的总量
例如:
- 技术笔记 2 遍
- CSDN 技术博客 3 篇
- 习的 vlog 视频 1 个