網(wǎng)站首頁 編程語言 正文
一、手工導(dǎo)出導(dǎo)出
1、winform
void DataGridViewToExcel(DataGridView dataGridView1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存為Excel文件";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream stream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += "\t";//或者為逗號(hào)
}
columnTitle += dataGridView1.Columns[i].HeaderText;//寫入列標(biāo)題
}
sw.WriteLine(columnTitle);
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
columnValue += "\t";
}
columnValue += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(columnValue);
}
sw.Close();
stream.Close();
}
finally
{
sw.Close();
stream.Close();
}
}
}
2、Web導(dǎo)出
不用存磁盤文件<iframe>導(dǎo)出。
string exportFileName = "Export" + DateTime.Now.ToString("yyyyMMddHHmmss");
System.Web.HttpContext context = System.Web.HttpContext.Current;
StringBuilder sb = new StringBuilder();
sb.Append("FirstName,LastName,PhoneNo.,State,TimeZone,ZipCode\n");
for (int i = 0; i < result.PhoneList.Count; i++)
{
sb.Append(result.PhoneList[i].FirstName + "," + result.PhoneList[i].LastName + "," + result.PhoneList[i].ZipCode + "\n");
}
StringWriter sw = new StringWriter(sb);//一定要StringWriter/StreamWriter才能直接導(dǎo)出
sw.Close();
context.Response.ClearHeaders();
context.Response.Clear();
context.Response.Charset = "UTF-8";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.HeaderEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = "text/csv";
context.Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF });//防止中文亂碼
context.Response.Write(sw);
context.Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode("1.csv", System.Text.Encoding.UTF8).Replace("+", "%20"));
sw.Close();
context.Response.Flush();
context.Response.End();
二、利用LumenWorks.Framework.IO.Csv讀取CSV文件
需要引用LumenWorks.Framework.IO.dll,讀取的時(shí)候編碼格式要選對(duì),否則會(huì)亂碼,表頭自己設(shè)置
- phatcher/CsvReader: Extended version of Sebastian Lorien's fast CSV Reader (github.com)
- NuGet Gallery | LumenWorksCsvReader 4.0.0
static DataTable GetData(Stream stream)
{
using (stream)
{
using (StreamReader input = new StreamReader(stream, Encoding.GetEncoding("shift_jis")))
{
using (CsvReader csv = new CsvReader(input, false))
{
DataTable dt = new DataTable();
int columnCount = csv.FieldCount;
for (int i = 0; i < columnCount; i++)
{
dt.Columns.Add("col" + i.ToString());
}
while (csv.ReadNextRecord())
{
DataRow dr = dt.NewRow();
for (int i = 0; i < columnCount; i++)
{
if (!string.IsNullOrWhiteSpace(csv[i]))
{
dr[i] = csv[i];
}
}
dt.Rows.Add(dr);
}
return dt;
}
}
}
}
基本使用場(chǎng)景
using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
// open the file "data.csv" which is a CSV file with headers
using (CsvReader csv =
new CsvReader(new StreamReader("data.csv"), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
while (csv.ReadNextRecord())
{
for (int i = 0; i < fieldCount; i++)
Console.Write(string.Format("{0} = {1};",
headers[i], csv[i]));
Console.WriteLine();
}
}
}
復(fù)雜的數(shù)據(jù)綁定方案(Windows窗體)
using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
// open the file "data.csv" which is a CSV file with headers
using (CachedCsvReader csv = new
CachedCsvReader(new StreamReader("data.csv"), true))
{
// Field headers will automatically be used as column names
myDataGrid.DataSource = csv;
}
}
原文鏈接:https://www.cnblogs.com/springsnow/p/11271571.html
相關(guān)推薦
- 2022-08-25 C++淺析STL?迭代器?容器的使用_C 語言
- 2022-06-12 postgreSQL數(shù)據(jù)庫(kù)基本概念教程_PostgreSQL
- 2022-10-01 iOS實(shí)現(xiàn)UIButton的拖拽功能_IOS
- 2022-05-28 教你C#將CSV轉(zhuǎn)為Excel的實(shí)現(xiàn)方法_C#教程
- 2022-05-14 python中opencv支持向量機(jī)的實(shí)現(xiàn)_python
- 2023-05-22 pytorch的Backward過程用時(shí)太長(zhǎng)問題及解決_python
- 2022-06-16 詳解Python如何循環(huán)遍歷Numpy中的Array_python
- 2022-12-12 pycharm?console?打印中文為亂碼問題及解決_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支