C#读取EXCEL列数据,并画折线图(刚开始⼊门⼩⽩⾃⼰整理的,⽅便⾃⼰以
后看)
⾸先建⽴⼀个c#dll⽂件,添加代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.Reflection;
namespace ClassLibrary3
{
public class Class1
{
#region 获取Excel某列数据
/// <summary>
/// 获取Excel某列数据
/// </summary>
/// <param name="ExcelName"></param>
public List<string> ColumnDB = new List<string>();
public List<string> getColumnDB(string ExcelName)
{
//创建 Excel对象
Application App = new Application();
//获取缺少的object类型值
object missing = Missing.Value;
//打开指定的Excel⽂件
Workbook openwb = App.Workbooks.Open(ExcelName, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
//获取选选择的⼯作表
Worksheet ws = ((Worksheet)openwb.Worksheets["Sheet1"]);//⽅法⼀:指定⼯作表名称读取
//Worksheet ws = (Worksheet)_Item(1);//⽅法⼆:通过⼯作表下标读取
/
/获取⼯作表中的⾏数
int rows = ws.UsedRange.Rows.Count;
//获取⼯作表中的列数
int columns = ws.UsedRange.Columns.Count;
int columns = ws.UsedRange.Columns.Count;
// Console.WriteLine("请输⼊你要获取哪列数据");
// int column = Convert.ToInt16(Console.ReadLine());
int column = 2;
//提取对应⾏列的数据并将其存⼊数组中
for(int i=1;i<=rows;i++)
{
string a = ((Range)ws.Cells[i, column]).Text.ToString();
// Console.WriteLine("读取的数据:" + a);//测试是否获得数据
ColumnDB.Add(a);
}
/* for (int i = 0; i < rows; i++)
{
Console.WriteLine(ColumnDB[i]);
}
*/
return ColumnDB;
//遍历数组
/
*
foreach (string db in ColumnDB)
{
Console.WriteLine("列表中的数据"+db);//查看数组中的数据,测试是否存储成功
}
Console.ReadLine();
*
*/
}
#endregion
}
}
此处借鉴:blog.csdn/kevinfan2011/article/details/83960232 ⼤佬代码
稍作修改,注释的⾮常清楚:
public List ColumnDB = new List();
泛型,字符串类型,创建了⼀个容量可根据需要⾃动扩充的列表
Workbooks.Open⽅法(Excel):
Excel.Workbook workbook = ExcelApplication.Workbooks.Open(fileName)
参考:wwwblogs/ilookbo/p/5531698.html
接下来,右键解决⽅案,到管理解决⽅案的NUGET包(若VS2010没有,可以再添加,可⾃⾏搜索),在⾥⾯搜索excel
接下来⽣成解决⽅案,即创建完dll
新建项⽬,添加⼯具:按钮、chart,布局如下
添加代码,我将所有代码都附上了:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClassLibrary3;
namespace Curve
打开excel很慢{
public partial class Form1 : Form
{
int count = 0;
List data = new List();
List dataFloat = new List();
private void updateChart()
{
chart1.Series[0].Points.Clear();
for (int i = 0; i < count; i++)
{
chart1.Series[0].Points.AddXY(i, dataFloat[i]);
}
}
/
/更新chart表格
public Form1()
{
InitializeComponent();
}
private void btn_DrawSignal_Click(object sender, EventArgs e)
{
Class1 hanshu = new Class1();
data = ColumnDB("C:/Users/ASUS/Desktop/6.xlsx");
foreach (var v in data)
{
count++;
}
//遍历data列表,出列表元素数⽬
for (int i = 0; i < count; i++)
{
dataFloat.Add(Convert.ToSingle(data[i])); //将string类型强制转换为double }
updateChart();
}
}
}
运⾏即可:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论