着急,c#操作excel 问题,求解啊!!!

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了着急,c#操作excel 问题,求解啊!!!相关的知识,希望对你有一定的参考价值。

Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 这句没错(开始都出错了,后来我网上找方法把互操作类型改成false就好了)
关键的地方到了: excel.Application.Workbooks.Add(true); 这个excel报错了啊,说 excel is a field but use like a type~ 我擦,咋回事啊
Microsoft.Office.Interop.Excel 这个组件我已经引进来了,可是依然无法用using Excel ,这我也就不在乎了,网上说直接用Microsoft.Office.Interop.Excel这个就行,但是excel咋还错了呢
Vivian陈薇
我那边的代码也试了,哪次都是到
ApplicationClass myExcel = new ApplicationClass();
Worksheet worksheet = null;
object missing = System.Reflection.Missing.Value;
myExcel.Workbooks.Add(missing); 这里 又说myExcel is a field but used like a type ,我自己觉得应该是包没引对,我解决不了了, “ is a field but used like a type”这句话快恶心死我了。。。 我引的包是Microsoft Excel 14.0 Object Library 可能是因为我Excel 版本高吧(win8 默认的)

其他大神也帮我看一下呗

参考技术A using System;
using System.IO;
using System.Text;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.Odbc;
using System.Collections.Generic;
using Microsoft.Office.Interop.Excel;
using System.Web;
using System.Data.OleDb;
//using cfg = System.Configuration;
namespace WX.Common

/// <summary>
/// Excel数据操作类
/// </summary>
public class ExcelHelper

//定义变量的缺省值
private static object mValue = System.Reflection.Missing.Value;

/// <summary>
/// 导出CVS文件数据
/// </summary>
/// <param name="fileName"></param>
/// <param name="path"></param>
/// <returns></returns>
public static DataSet ConnectCSVFile(string fileName, string path)

string strConn = @"Driver=Microsoft Text Driver (*.txt; *.csv);Dbq=";
strConn += path;
strConn += ";Extensions=asc,csv,tab,txt;HDR=Yes;Persist Security Info=False";
OdbcConnection objConn = new OdbcConnection(strConn);
DataSet ds = new DataSet();
try

string strSql = "select * from " + fileName; //fileName, For example: 1.csv
OdbcDataAdapter odbcCSVDataAdapter = new OdbcDataAdapter(strSql, objConn);
odbcCSVDataAdapter.Fill(ds);

catch (Exception ex)

throw ex;

finally

System.GC.Collect();


return ds;


/// <summary>
/// 导出Excel文件
/// </summary>
/// <param name="filepath"></param>
/// <param name="ExcelName"></param>
/// <returns></returns>
/// IMEX=1将强制混合数据转换为文本,HDR=NO将第一行作为内容,由于第一行Header都是文本,因此所有列的类型都将转换成文本。

public static DataSet ExcelToDataTable(string filepath, string sheetName)

string strConn = string.Empty;
string type = filepath.Substring(filepath.LastIndexOf('.') + 1, filepath.Length - filepath.LastIndexOf('.') - 1);
if (type == "xlsx")

strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";

else

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1;HDR=YES'";

System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strConn);
string strCom = "SELECT * FROM " + "[" + sheetName.Replace('#', '.').Replace("$", "").Replace("'","") + "$]";//读取Excel文件内容
Conn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
DataSet ds = new DataSet();
myCommand.Fill(ds, sheetName);
Conn.Close();
return ds;



/// <summary>
/// 导入Excel文件
/// </summary>
/// <param name="tmpDataTable"></param>
/// <param name="strFileName"></param>
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)

//检查进程
List<Process> excelProcesses = GetExcelProcesses();
if (excelProcesses.Count > 0)

//杀死进程
KillTheExcel();


Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
try

if (tmpDataTable == null)
return;
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = 1;//如果需要导出列名,设置为1,否则设置为0
int columnIndex = 0;

xlApp.DefaultFilePath = "";
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
xlApp.SheetsInNewWorkbook = 1;

Excel.Worksheet ExcelSheet = (Worksheet)xlBook.Worksheets[1];
ExcelOperate operate = new ExcelOperate();
operate.SetBold(ExcelSheet, ExcelSheet.Cells[1, 1], ExcelSheet.Cells[1, columnNum]);
operate.SetHAlignCenter(ExcelSheet, ExcelSheet.Cells[1, 1], ExcelSheet.Cells[rowNum + 1, columnNum]);//居中
ExcelSheet.Columns.EntireRow.AutoFit();
ExcelSheet.Rows.EntireColumn.AutoFit();
//将DataTable的列名导入Excel表第一行(如果需要可以加上)
foreach (DataColumn dc in tmpDataTable.Columns)

columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;


//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)

rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)

columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();



//保存
xlBook.SaveAs(strFileName, mValue, mValue, mValue, mValue, mValue, Excel.XlSaveAsAccessMode.xlShared
, mValue, mValue, mValue, mValue, mValue);

catch (Exception ex)

throw ex;


finally

xlApp.Workbooks.Close();
//关闭进程,自动保存
xlApp.Quit();
System.GC.Collect();



public static string ExcelSheetName(string filepath)

string al = string.Empty;
string strConn;
string type = filepath.Substring(filepath.LastIndexOf('.') + 1, filepath.Length - filepath.LastIndexOf('.') - 1);
if (type == "xlsx")

strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";

else

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1;HDR=YES'";

OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
System.Data.DataTable sheetNames = conn.GetOleDbSchemaTable
(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] null, null, null, "TABLE" );
conn.Close();
if (sheetNames.Rows.Count > 0)

al = sheetNames.Rows[0][2].ToString();
if (!string.IsNullOrEmpty(al))

al = al.Substring(0, al.Length - 1);


//foreach (DataRow dr in sheetNames.Rows)
//
// al = dr[2].ToString();
// if (!string.IsNullOrEmpty(al))
//
// al = al.Substring(0, al.Length - 1);
//
//
return al;


public void ExportExcel(System.Data.DataTable dt, StreamWriter w)

try

for (int i = 0; i < dt.Columns.Count; i++)

w.Write(dt.Columns[i]);
w.Write(' ');

w.Write(" ");

object[] values = new object[dt.Columns.Count];
foreach (DataRow dr in dt.Rows)

values = dr.ItemArray;
for (int i = 0; i < dt.Columns.Count; i++)

w.Write(values[i]);
w.Write(' ');

w.Write(" ");

w.Flush();
w.Close();

catch

w.Close();



/// <summary>
/// 获得进程
/// </summary>
/// <returns></returns>
private static List<Process> GetExcelProcesses()

//获得当前计算机的进程列表
Process[] processes = Process.GetProcesses();
//保存Excel进程
List<Process> ListProcess = new List<Process>();

foreach (Process _pr in processes)

if (_pr.ProcessName.ToUpper().Equals("EXCEL"))

ListProcess.Add(_pr);


return ListProcess;


/// <summary>
/// 销毁所有Excel进程
/// </summary>
public static void KillTheExcel()

List<Process> listProcess = GetExcelProcesses();
foreach (Process _pr in listProcess)

_pr.Kill();



/// <summary>
/// 释放内存
/// </summary>
public void Dispose(Excel._Worksheet CurSheet, Excel._Workbook CurBook, Excel._Application CurExcel)

try

System.Runtime.InteropServices.Marshal.ReleaseComObject(CurSheet);
CurSheet = null;
CurBook.Close(false, Missing.Value, Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(CurBook);
CurBook = null;

CurExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(CurExcel);
CurExcel = null;

GC.Collect();
GC.WaitForPendingFinalizers();

catch (System.Exception ex)

HttpContext.Current.Response.Write("在释放Excel内存空间时发生了一个错误:" + ex);

finally

foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("Excel"))
pro.Kill();

System.GC.SuppressFinalize(this);


参考技术B 参考一下这个http://zhidao.baidu.com/question/1574061821047183860.html?oldq=1追问

我那边的代码也试了,哪次都是到 myExcel.Workbooks.Add(missing); 这里 又说myExcel is a field but used like a type ,我自己觉得应该是包没引对,我解决不了了

追答

需要添加COM组件 Interop.Excel.dll,Interop.Microsoft.Office.Core.dll,你添加了吗

追问

Microsoft.Office.Interop.Excel 引了

参考技术C 为什么用这个技术啊,这不是要启动excel进程吗,不复杂的话用NOPI足够用了。追问

您能说的再具体一点吗? NOPI怎么引,基本操作之类的~~~

追答

nopi是一个组件。dll格式的,你把它挎到你项目目录下,随便指个目录都可以。然后,添加引用,选择所有的dll就可以了,低版本的nopi的dll有好几个,都要引入,高版本好象就一个。具体引用以后,使用的方法,我给你个地址:http://user点qzone点qq点com/315426452/blog/1385110354。这个里面有它的使用方法,把地址里的点换成点符号,你明白的,要不百度会过滤的。至于NOPI,你到网上搜索一下。或是用这个http://pan.baidu.com/s/1ntz5E8T,呵,祝你成功

本回答被提问者采纳

C#程序中操作Excel的问题?

怎样把程序中的表格式是数据导出到Excel中去,Excel 的api文档那里有啊,

多给点分吗? 这是一个sample。。。。

public partial class Window1 : Window

DataTable dt = new DataTable();
object misValue = System.Reflection.Missing.Value;
public Window1()

InitializeComponent();
dt.Columns.Add("AA", typeof(string));
dt.Columns.Add("BB", typeof(string));
dt.Rows.Add("11", "22");
dt.Rows.Add("33", "44");

this.dataGrid1.ItemsSource = ((IListSource)dt).GetList();


private void Button_Click(object sender, RoutedEventArgs e)

#region
Microsoft.Office.Interop.Excel.Application app=null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
Microsoft.Office.Interop.Excel.Worksheet ws=null;
try

app = new Microsoft.Office.Interop.Excel.Application();
wb = app.Workbooks.Add(misValue);
ws = app.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Range range;

range = ws.get_Range("A2", misValue);
range = range.get_Resize(dt.Rows.Count, dt.Columns.Count);

Microsoft.Office.Interop.Excel.Range columnNameRange;
columnNameRange = ws.get_Range("A1", misValue);
columnNameRange = columnNameRange.get_Resize(1, dt.Columns.Count);

string[] columNames = new string[dt.Columns.Count];

for(int i=0;i<dt.Columns.Count;i++)
columNames[i] = dt.Columns[i].ColumnName;
columnNameRange.set_Value(misValue, columNames);

string[,] arr = new string[dt.Rows.Count, dt.Columns.Count];
for (int i = 0; i < dt.Rows.Count; i++)

for (int j = 0; j < dt.Columns.Count; j++)

arr[i, j] = dt.Rows[i][j].ToString();


range.set_Value(misValue, arr);
wb.Close(true, "D:\\Test.xlsx", misValue);

catch (Exception ex)

Trace.WriteLine(ex.Message.ToString());

finally

// make sure the office process quit after certain operations done.
if (app != null)

app.UserControl = false;
app.Quit();
app = null;


#endregion

参考技术A C#貌似不需要API就可以做到,用连接字符串可以直接读取到文件的内容,不过写入就不太清楚了 参考技术B 这段代码 修改下 应该能用

/// <summary>
/// 执行导出
/// </summary>
/// <param name="ds">要导出的DataSet</param>
/// <param name="strExcelFileName">要导出的文件名(详细路径加文件名)</param>
private static void doExport(DataSet ds, string strExcelFileName)

Excel.Application excel = new Excel.Application();
if (excel == null)

MessageBox.Show("无法启动Excel,可能您的电脑未安装Excel");
return;

try

int rowIndex = 1;
int colIndex = 0;

excel.Application.Workbooks.Add(true);

System.Data.DataTable table = ds.Tables[0];
foreach (DataColumn col in table.Columns)

colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;


foreach (DataRow row in table.Rows)

rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)

colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();


excel.Visible = false;
//excel.Sheets[0] = "消息";
excel.DisplayAlerts = false;
excel.ActiveWorkbook.SaveCopyAs(strExcelFileName);

excel.Quit();
excel = null;
MessageBox.Show("数据导出成功!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);


catch (Exception ex)

MessageBox.Show(ex.ToString());

finally

GC.Collect();//垃圾回收

参考技术C //导出:
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);

for (int i = 1; i <= dt.Columns.Count; i++)//打印表头

excel.Cells[1, i] = dt.Columns.ColumnName.ToString();

for (int i = 2; i <= dt.Rows.Count + 1; i++)//打印表的内容

for (int j = 1; j <= dt.Columns.Count; j++)

excel.Cells = dt.Rows[j - 1].ToString();


excel.Visible = true;
//导入:
if (this.DataGrid1.Items.Count != 0)

try

for (int i = 0; i < this.DataGrid1.Items.Count; i++)

model_result.CouseId = int.Parse(this.ddlCourse.SelectedValue.ToString());
model_result.StudentId = this.DataGrid1.Items.Cells[0].Text;
model_result.Terms = this.ddlTerms.SelectedItem.Text;

if (bll_grade.Judge_SomeOne_Student_Is_Have_Exist(model_result))

model_result.TotalScore = float.Parse(this.DataGrid1.Items.Cells[2].Text);
bll_grade.Insert_Student_TotalScore_Online(model_result);



Response.Write("<script>alert('导入成功!');</script>");

catch

Response.Write("<script>alert('导入失败!');</script>");



我空间的日志

以上是关于着急,c#操作excel 问题,求解啊!!!的主要内容,如果未能解决你的问题,请参考以下文章

excel表格里面的数字突然全部变成了#VALUE是怎么回事啊?要怎么恢复成文本,着急。谢谢!!

急!!!matlab求解假设检验,为啥出现一堆数呀不应该是一个值么?1小时内翻倍呀!!!

excel2003中一组新的数据怎么覆盖新的数据?求解 不清楚的还可再问

我的百度i贴吧打不开 有问题啊 求解啊 纠结

Excel规划求解求哪几个数字之和等于一个固定值

EXCEL VBA中规划求解器Solver出现 运行错误‘1004’应用程序定义或对象定义错误