如何解决对象引用未设置为对象实例的错误
本文关键字:设置 对象 实例 错误 对象引用 何解决 解决 | 更新日期: 2023-09-27 18:34:38
我正在制作一个程序来将csv(通用选择值文件(文件转换为xls(Microsoft Excel文件(文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConversionToXLSFile
{
public partial class Converter : System.Web.UI.Page
{
//Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
protected void Page_Load(object sender, EventArgs e)
{
//List<string> row = new List<string>();
string fullPath = @"D:'Work'Sep-14'ConversionToXLSFile'ConversionToXLSFile'File'diff_16122014095440.csv";
string[] fileRows = File.ReadAllLines(fullPath, Encoding.UTF8);
foreach (string rows in fileRows)
{
var columns = rows.Split(';');
for (int j = 0; j < fileRows.Length; j++)
{
for (int i = 0; i < columns.Length; i++)
{
List<string> elements = new List<string>();
foreach (string col in columns)
{
elements.Add(col);
xlWorkSheet.Cells[j, i] = col;
}
}
}
}
xlWorkBook.SaveAs("d:''csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void Add(dynamic dynamic)
{
throw new NotImplementedException();
}
}
}
据我所知,您已经注释掉了分配变量 xlApp、xlWorkBook 和 xlWorksheet 的代码......
//Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
//xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
从每一行中取出//,当您尝试使用它们时,您不会得到空引用异常。