मुझे बिना किसी एएसपी कोड (एचटीपीआरएसओपीएस ...) के बिना एक्सेल फ़ाइल में डेटासेट निर्यात करने का समाधान चाहिए, लेकिन मुझे ऐसा करने के लिए एक अच्छा उदाहरण नहीं मिला ...सी # (WinForms-App) एक्सेल को डेटासेट निर्यात
बेस्ट धन्यवाद अग्रिम
मुझे बिना किसी एएसपी कोड (एचटीपीआरएसओपीएस ...) के बिना एक्सेल फ़ाइल में डेटासेट निर्यात करने का समाधान चाहिए, लेकिन मुझे ऐसा करने के लिए एक अच्छा उदाहरण नहीं मिला ...सी # (WinForms-App) एक्सेल को डेटासेट निर्यात
बेस्ट धन्यवाद अग्रिम
में मैं एक वर्ग है कि एक DataGridView
या DataTable
निर्यात करता है एक एक्सेल फाइल करने के लिए बनाया है। आप इसके बजाय इसे अपने DataSet
का उपयोग करने के लिए इसे थोड़ा सा बदल सकते हैं (इसमें DataTables
के माध्यम से पुनरावृत्ति)। यह कुछ बुनियादी प्रारूपण भी करता है जिसे आप भी बढ़ा सकते हैं।
इसका उपयोग करने के लिए, बस ExcelExport पर कॉल करें, और एक फ़ाइल नाम निर्दिष्ट करें और फ़ाइल को स्वचालित रूप से खोलने के बाद या निर्यात के बाद नहीं। मैं उन्हें विस्तार विधियां भी बना सकता था, लेकिन मैंने नहीं किया। निसंकोच।
ध्यान दें कि एक्सेल फ़ाइलों को एक गौरवशाली XML दस्तावेज़ के रूप में सहेजा जा सकता है और इससे इसका उपयोग होता है।
संपादित करें: यह एक वेनिला StreamWriter
का उपयोग करता था, लेकिन जैसा कि बताया गया है, कई मामलों में चीजें ठीक से नहीं बचेंगी। अब यह XmlWriter
का उपयोग करता है, जो आपके लिए भागने वाला होगा।
ExcelWriter
कक्षा XmlWriter
लपेटती है। मुझे परेशान नहीं है, लेकिन आप यह सुनिश्चित करने के लिए थोड़ा और त्रुटि जांचना चाहेंगे कि आप पंक्ति शुरू करने से पहले सेल डेटा नहीं लिख सकते हैं। कोड नीचे है।
public class ExcelWriter : IDisposable
{
private XmlWriter _writer;
public enum CellStyle { General, Number, Currency, DateTime, ShortDate };
public void WriteStartDocument()
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");
_writer.WriteStartElement("ss", "Workbook", "urn:schemas-microsoft-com:office:spreadsheet");
WriteExcelStyles();
}
public void WriteEndDocument()
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteEndElement();
}
private void WriteExcelStyleElement(CellStyle style)
{
_writer.WriteStartElement("Style", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteAttributeString("ID", "urn:schemas-microsoft-com:office:spreadsheet", style.ToString());
_writer.WriteEndElement();
}
private void WriteExcelStyleElement(CellStyle style, string NumberFormat)
{
_writer.WriteStartElement("Style", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteAttributeString("ID", "urn:schemas-microsoft-com:office:spreadsheet", style.ToString());
_writer.WriteStartElement("NumberFormat", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteAttributeString("Format", "urn:schemas-microsoft-com:office:spreadsheet", NumberFormat);
_writer.WriteEndElement();
_writer.WriteEndElement();
}
private void WriteExcelStyles()
{
_writer.WriteStartElement("Styles", "urn:schemas-microsoft-com:office:spreadsheet");
WriteExcelStyleElement(CellStyle.General);
WriteExcelStyleElement(CellStyle.Number, "General Number");
WriteExcelStyleElement(CellStyle.DateTime, "General Date");
WriteExcelStyleElement(CellStyle.Currency, "Currency");
WriteExcelStyleElement(CellStyle.ShortDate, "Short Date");
_writer.WriteEndElement();
}
public void WriteStartWorksheet(string name)
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteStartElement("Worksheet", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteAttributeString("Name", "urn:schemas-microsoft-com:office:spreadsheet", name);
_writer.WriteStartElement("Table", "urn:schemas-microsoft-com:office:spreadsheet");
}
public void WriteEndWorksheet()
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteEndElement();
_writer.WriteEndElement();
}
public ExcelWriter(string outputFileName)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
_writer = XmlWriter.Create(outputFileName, settings);
}
public void Close()
{
if (_writer == null) throw new InvalidOperationException("Already closed.");
_writer.Close();
_writer = null;
}
public void WriteExcelColumnDefinition(int columnWidth)
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteStartElement("Column", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteStartAttribute("Width", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteValue(columnWidth);
_writer.WriteEndAttribute();
_writer.WriteEndElement();
}
public void WriteExcelUnstyledCell(string value)
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteStartElement("Cell", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteStartElement("Data", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "String");
_writer.WriteValue(value);
_writer.WriteEndElement();
_writer.WriteEndElement();
}
public void WriteStartRow()
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteStartElement("Row", "urn:schemas-microsoft-com:office:spreadsheet");
}
public void WriteEndRow()
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteEndElement();
}
public void WriteExcelStyledCell(object value, CellStyle style)
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
_writer.WriteStartElement("Cell", "urn:schemas-microsoft-com:office:spreadsheet");
_writer.WriteAttributeString("StyleID", "urn:schemas-microsoft-com:office:spreadsheet", style.ToString());
_writer.WriteStartElement("Data", "urn:schemas-microsoft-com:office:spreadsheet");
switch (style)
{
case CellStyle.General:
_writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "String");
break;
case CellStyle.Number:
case CellStyle.Currency:
_writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "Number");
break;
case CellStyle.ShortDate:
case CellStyle.DateTime:
_writer.WriteAttributeString("Type", "urn:schemas-microsoft-com:office:spreadsheet", "DateTime");
break;
}
_writer.WriteValue(value);
// tag += String.Format("{1}\"><ss:Data ss:Type=\"DateTime\">{0:yyyy\\-MM\\-dd\\THH\\:mm\\:ss\\.fff}</ss:Data>", value,
_writer.WriteEndElement();
_writer.WriteEndElement();
}
public void WriteExcelAutoStyledCell(object value)
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
//write the <ss:Cell> and <ss:Data> tags for something
if (value is Int16 || value is Int32 || value is Int64 || value is SByte ||
value is UInt16 || value is UInt32 || value is UInt64 || value is Byte)
{
WriteExcelStyledCell(value, CellStyle.Number);
}
else if (value is Single || value is Double || value is Decimal) //we'll assume it's a currency
{
WriteExcelStyledCell(value, CellStyle.Currency);
}
else if (value is DateTime)
{
//check if there's no time information and use the appropriate style
WriteExcelStyledCell(value, ((DateTime)value).TimeOfDay.CompareTo(new TimeSpan(0, 0, 0, 0, 0)) == 0 ? CellStyle.ShortDate : CellStyle.DateTime);
}
else
{
WriteExcelStyledCell(value, CellStyle.General);
}
}
#region IDisposable Members
public void Dispose()
{
if (_writer == null)
return;
_writer.Close();
_writer = null;
}
#endregion
}
तो फिर आप अपने DataTable
निर्यात निम्नलिखित का उपयोग कर सकते हैं:
public static void ExcelExport(DataTable data, String fileName, bool openAfter)
{
//export a DataTable to Excel
DialogResult retry = DialogResult.Retry;
while (retry == DialogResult.Retry)
{
try
{
using (ExcelWriter writer = new ExcelWriter(fileName))
{
writer.WriteStartDocument();
// Write the worksheet contents
writer.WriteStartWorksheet("Sheet1");
//Write header row
writer.WriteStartRow();
foreach (DataColumn col in data.Columns)
writer.WriteExcelUnstyledCell(col.Caption);
writer.WriteEndRow();
//write data
foreach (DataRow row in data.Rows)
{
writer.WriteStartRow();
foreach (object o in row.ItemArray)
{
writer.WriteExcelAutoStyledCell(o);
}
writer.WriteEndRow();
}
// Close up the document
writer.WriteEndWorksheet();
writer.WriteEndDocument();
writer.Close();
if (openAfter)
OpenFile(fileName);
retry = DialogResult.Cancel;
}
}
catch (Exception myException)
{
retry = MessageBox.Show(myException.Message, "Excel Export", MessageBoxButtons.RetryCancel, MessageBoxIcon.Asterisk);
}
}
}
NET अनुप्रयोगों में एक्सेल फ़ाइलें बनाकर काफी सामान्य है और इसी तरह के सवाल कई बार कहा गया है पहले। उदाहरण के लिए here और here। आखिरी सवाल एक्सेल फाइल पढ़ने के बारे में पूछता है, लेकिन सबसे अधिक सुझाए गए समाधानों को दोनों तरीकों से काम करना चाहिए।
अगर मैं गलत हूं तो मुझे सही करें, लेकिन माव एक वेब सर्वर पर समाधान के लिए पूछ रहा था? –
आह। मैंने तब आपके प्रश्न को गलत समझा। मैंने सोचा था कि आप किसी भी कोड को लिखने के बिना एक्सेल फाइलें बनाने का एक तरीका मांग रहे थे। मैं तब अपना जवाब दोहरा दूंगा। –
निम्न साइट एक डेटासेट (या डेटाटेबल या सूची <>) को "वास्तविक" एक्सेल 2007 .xlsx फ़ाइल में निर्यात करने का तरीका दर्शाती है।
यह OpenXML पुस्तकालयों का उपयोग करता है, तो आप Excel अपने सर्वर पर स्थापित करने के लिए नहीं जरूरत करना ।
MikesKnowledgeBase - ExportToExcel
स्रोत कोड के सभी अच्छी तरह से एक डेमो आवेदन के रूप में प्रदान की जाती है, प्रभारी की मुक्त,।
यह बहुत अपने खुद के आवेदन करने के लिए जोड़ने के लिए आसान है, तो आप सिर्फ एक समारोह कॉल करने के लिए, एक एक्सेल फ़ाइल नाम में गुजर जरूरत है, और अपने डेटा स्रोत:
DataSet ds = CreateSampleData();
string excelFilename = "C:\\Sample.xlsx";
CreateExcelFile.CreateExcelDocument(ds, excelFilename);
आशा इस मदद करता है।
मैं इसका उपयोग कर रहा हूं। मुझे लाइसेंस समझौता नहीं मिला? – Melanie
using XL = Microsoft.Office.Interop.Excel;
using System.Reflection;
public static void Datasource(DataTable dt)
{
XL.Application oXL;
XL._Workbook oWB;
XL._Worksheet oSheet;
XL.Range oRng;
try
{
oXL = new XL.Application();
Application.DoEvents();
oXL.Visible = false;
//Get a new workbook.
oWB = (XL._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (XL._Worksheet)oWB.ActiveSheet;
//System.Data.DataTable dtGridData=ds.Tables[0];
int iRow = 2;
if (dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
oSheet.Cells[1, j + 1] = dt.Columns[j].ColumnName;
}
// For each row, print the values of each column.
for (int rowNo = 0; rowNo < dt.Rows.Count; rowNo++)
{
for (int colNo = 0; colNo < dt.Columns.Count; colNo++)
{
oSheet.Cells[iRow, colNo + 1] = dt.Rows[rowNo][colNo].ToString();
}
iRow++;
}
iRow++;
}
oRng = oSheet.get_Range("A1", "IV1");
oRng.EntireColumn.AutoFit();
oXL.Visible = true;
}
catch (Exception theException)
{
throw theException;
}
finally
{
oXL = null;
oWB = null;
oSheet = null;
oRng = null;
}
}
Import from Excel to datatable
DataTable dtTable = new DataTable();
DataColumn col = new DataColumn("Rfid");
dtTable.Columns.Add(col);
DataRow drRow;
Microsoft.Office.Interop.Excel.Application ExcelObj =
new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook theWorkbook =
ExcelObj.Workbooks.Open(txt_FilePath.Text, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
try
{
for (int sht = 1; sht <= sheets.Count; sht++)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet =
(Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(sht);
for (int i = 2; i <= worksheet.UsedRange.Rows.Count; i++)
{
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A" + i.ToString(), "B" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value2;
String name = Convert.ToString(myvalues.GetValue(1, 1));
if (string.IsNullOrEmpty(name) == false)
{
drRow = dtTable.NewRow();
drRow["Rfid"] = name;
dtTable.Rows.Add(drRow);
}
}
Marshal.ReleaseComObject(worksheet);
worksheet = null;
}
return dtTable;
}
catch
{
throw;
}
finally
{
// Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(sheets);
Marshal.ReleaseComObject(theWorkbook);
Marshal.ReleaseComObject(ExcelObj);
//worksheet = null;
sheets = null;
theWorkbook = null;
ExcelObj = null;
}
अपने कोड के लिए कुछ स्पष्टीकरण शामिल करने का प्रयास करें। –
यह एक सच में मददगार शीर्ष जवाब के साथ एक पद था, लेकिन मैंने पाया क्योंकि वहाँ एक्सएमएल फ़ाइल एक datatable में वापस आयात करने के लिए कोई आसान तरीका था यह कमी है।मैं अपने खुद के लिखने के लिए होने समाप्त हो गया है, और सोचा था कि मैं इसे यहाँ मामला किसी में साझा करेंगे और कुछ ही नाव में था (गूगल इस संबंध में असाधारण बेकार था):
public static DataTable ImportExcelXML(string Filename)
{
//create a new dataset to load in the XML file
DataSet DS = new DataSet();
//Read the XML file into the dataset
DS.ReadXml(Filename);
//Create a new datatable to store the raw Data
DataTable Raw = new DataTable();
//assign the raw data from the file to the datatable
Raw = DS.Tables["Data"];
//count the number of columns in the XML file
int ColumnNumber = Raw.Columns.Count;
//create a datatable to store formatted Import Data
DataTable ImportData = new DataTable();
//create a string list to store the cell data of each row
List<string> RowData = new List<string>();
//loop through each row in the raw data table
for (int Counter = 0; Counter < Raw.Rows.Count; Counter++)
{
//if the data in the row is a colum header
if (Counter < ColumnNumber)
{
//add the column name to our formatted datatable
ImportData.Columns.Add(Raw.Rows[Counter].ItemArray.GetValue(1).ToString());
}
else
{
//if the row # (1 row = 1 cell from the excel file) from the raw datatable is divisable evenly by the number of columns in the formated import datatable AND this is not the 1st row of the raw table data after the headers
if ((Counter % ColumnNumber == 0) && (Counter != ColumnNumber))
{
//add the row we just built to the formatted import datatable
ImportData.Rows.Add(GenerateRow(ImportData, RowData));
//clear rowdata list in preperation for the next row
RowData.Clear();
}
//add the current cell data value from the raw datatable to the string list of cell values for the next row to be added to the formatted input datatable
RowData.Add(Raw.Rows[Counter].ItemArray.GetValue(1).ToString());
}
}
//add the final row
ImportData.Rows.Add(GenerateRow(ImportData, RowData));
return ImportData;
}
public static DataRow GenerateRow(DataTable ImportData, List<string> RowData)
{
//create a counter to keep track of the column position during row composition
int ColumnPosition = 0;
//make a new datarow based on the schema of the formated import datatable
DataRow NewRow = ImportData.NewRow();
//for each string cell value collected for the RowData list for this row
foreach (string CellData in RowData)
{
//add the cell value to the new datarow
NewRow[ImportData.Columns[ColumnPosition].ColumnName] = CellData;
//incriment column position in the new row
ColumnPosition++;
}
//return the generated row
return NewRow;
}
कोड शून्य मान के साथ समस्या है।
public void WriteExcelAutoStyledCell(object value)
{
//solve null values
if (value is DBNull) return;
मैं इसे टिप्पणियों में जोड़ता था लेकिन मैं ढेर करने के लिए नया हूं इसलिए मैं टिप्पणी करने में असमर्थ हूं। एलसी। समाधान का उपयोग करके मैंने एक और फ़ंक्शन जोड़ा जो अमान्य XML वर्णों के लिए स्ट्रिंग वर्णों का परीक्षण करता है। जब मैं अवसर पर उत्कृष्टता के लिए निर्यात कर रहा था वहां ऐसे पात्र थे जो निर्यात को विफल करने के कारण थे।
आपको एलसी कोड में मौजूद कार्यों में से एक को संशोधित करने की आवश्यकता होगी।
public void WriteExcelAutoStyledCell(object value)
{
if (_writer == null) throw new InvalidOperationException("Cannot write after closing.");
string newValue = string.Empty;
try
{
//write the <ss:Cell> and <ss:Data> tags for something
if (value is Int16 || value is Int32 || value is Int64 || value is SByte ||
value is UInt16 || value is UInt32 || value is UInt64 || value is Byte)
{
WriteExcelStyledCell(value, CellStyle.Number);
}
else if (value is Single || value is Double || value is Decimal) //we'll assume it's a currency
{
WriteExcelStyledCell(value, CellStyle.Currency);
}
else if (value is DateTime)
{
//check if there's no time information and use the appropriate style
WriteExcelStyledCell(value, ((DateTime)value).TimeOfDay.CompareTo(new TimeSpan(0, 0, 0, 0, 0)) == 0 ? CellStyle.ShortDate : CellStyle.DateTime);
}
else
{
newValue = CheckXmlCompatibleValues(value.ToString()).ToString();
WriteExcelStyledCell(newValue, CellStyle.General);
}
}
catch (Exception thisException)
{
throw new InvalidOperationException(thisException.Message.ToString());
}
}
और 'ExcelWriter' वर्ग
public string CheckXmlCompatibleValues(string value)
{
string newValue = string.Empty;
bool found = false;
foreach (char c in value)
{
if (XmlConvert.IsXmlChar(c))
newValue += c.ToString();
else
found = true;
}
return newValue.ToString();
}
नियंत्रण रेखा को यह समारोह जोड़ें। कोड के लिए धन्यवाद!
माइक्रोसॉफ्ट के पास एक्सेल फ़ाइलों को आयात/निर्यात करने के लिए समाधान में बनाया गया है। यह सबसे सरल लाइब्रेरी नहीं है लेकिन यह आमतौर पर ऊपर सूचीबद्ध अन्य लोगों की तुलना में बेहतर काम करता है।
ऐसा करने के लिए आवश्यक लाइब्रेरी को Office में शामिल किया गया है और Microsoft.Office.Interop.Excel पर फ्रेमवर्क असेंबली की सूची के तहत पाया जा सकता है।
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application app = new Excel.Application();
//Open existing workbook
//Excel.Workbook workbook = xlApp.Workbooks.Open(fileName);
//Create new workbook
Excel.Workbook workbook = app.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet;
worksheet.Cells[1,1] = "Hello world!"; // Indexes start at 1, because Excel
workbook.SaveAs("C:\\MyWorkbook.xlsx");
workbook.Close();
app.Quit();
-1:
यहाँ कुछ उदाहरण कोड है इस तरह से एक TextWriter का उपयोग कर एक्सएमएल उत्पन्न करने के लिए प्रयास न करें। मैं सिर्फ एक स्पष्ट समस्या को इंगित करूंगा: यदि आपके डेटाटेबल में कोण ब्रैकेट के साथ एक स्ट्रिंग मान होता है, तो उपर्युक्त कोड उन्हें ठीक से नहीं बच पाएगा। – Joe
अच्छा बिंदु। बस दिखाने के लिए चला जाता है मुझे थोड़ा और सोचने से रोकना चाहिए। मैंने इसे XmlWriter का उपयोग करने के लिए फिर से बनाया है। सैद्धांतिक रूप से, किसी को सार्वजनिक पुस्तकालय में इसे रिलीज़ करने से पहले थोड़ा और त्रुटि जांच करनी चाहिए, लेकिन यदि आप सुनिश्चित हैं कि आप सही क्रम में चीजें कॉल करेंगे तो आप "सुरक्षित" हैं। –
कोड के दूसरे भाग में एक गलती है। 'Foreach (dataTable.Rows में ऑब्जेक्ट ओ' के बजाय 'foreach (पंक्ति में वस्तु ओ। IememArray) होना चाहिए। – Aleris