|
哎呀,我又来烦请大家了,由于是新学的C#对于变量不是很熟悉,可是现在又很急了,还请大家帮我改下这个代码,
导入excel
比如我有个excel已经有这样的 固定格式了,我想导入到ListView中,是不是变量{:soso_e109:}错了?要怎么修改。。谢谢了啊。好急..代码如下:
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 Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
namespace 导入导出excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet ds = new DataSet(); //全局变量
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
string filename = ofd.FileName;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
object oMissing = System.Reflection.Missing.Value;//相当null
workbook = excel.Workbooks.Open(filename, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
worksheet = (Worksheet)workbook.Worksheets[1];
int rowCount = worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;
Microsoft.Office.Interop.Excel.Range range1;
System.Data.DataTable dt = new System.Data.DataTable();
for (int i = 0; i < colCount; i++)
{
range1 = worksheet.get_Range(worksheet.Cells[1, i + 1], worksheet.Cells[1, i + 1]);
dt.Columns.Add(range1.Value2.ToString());
}
for (int j = 1; j < rowCount; j++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < colCount; i++)
{
range1 = worksheet.get_Range(worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]);
dr = range1.Value2.ToString();
}
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
excel.Quit();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|
|