text:
Q: How to plot the text on top of each plot rather than inside the plot in ggplot? I have a df like this:
Name <- c('A','A','A','A','A','A','A','A','A','A')
Measurement <- c('Length','Length','Length','Length','Length','Length','Length','Length','Length','Length')
Meas_Avg <- c(0.125,0.150,0.122,0.177,0.145,0.135,0.180,0.133,0.174,0.149)
Tool <- c('Tool1','Tool3','Tool2','Tool3','Tool3','Tool1','Tool1','Tool2','Tool2','Tool1')

df <- data.frame(Name,Measurement,Meas_Avg,Tool)
pvalue <- 0.056

and I have a text "pvalue" that I manually position inside a ggplot while plotting. While this seems good for one plot, but if I were to use it for the rest of the plots, this way of doing it is not right since the values in the plot change and the boxplots move all over the plotting area. Here is my ggplot function
ggplot(data = df, aes(x=Tool, y=Meas_Avg)) +
  theme(axis.text=element_text(size=14)
        , axis.title=element_text(size=14,face="bold")) +
  geom_boxplot(outlier.colour = "red", outlier.size=3, outlier.shape=15, fill="gray95", colour="blue") +
  geom_point(alpha=0.6, position=position_jitter(w=0.05, h=0.0), aes(colour=Tool), size=5) +
  facet_grid(Measurement~Name,scales = "free", space = "free") +
  scale_color_manual(values = c("red", "magenta", "dodgerblue2","green","blue","orange","black","violet")) +
  scale_size_area() +
  geom_text(data = pval_TAP_5, aes(label=paste("pvalue= ",pvalue), x=2.0, y=0.25),size=7) +
  theme(strip.text.x = element_text(size = 15, colour = "red",face="bold")
        ,strip.text.y = element_text(size = 15, colour = "red",face="bold"))

This obtains

I would like to plot the text "pvalue = 0.056"  on top of the plot (here in this case on top of "A" rather than manually doing it inside. How can this be achieved?

A: You could try renaming the Name column as below:
df$Name <- paste0(df$Name, "\n pvalue = ", pvalue)


text:
Q: RadioButton wont set checked javascript I dont know why the radiobutton wont set checked. I tried all the methods i could find but it won't work.
How I want it to work is that Type1 radiobutton is set checked if the value is 1; if the value is 0, Type2 radiobutton is set checked.
I printed the value in a textfield. The value is from a database btw. Nothing's wrong with getting the value from the database and printing it in the textfield.
My only problem is setting the radio buttons checked based on the value in the textfield.
I put an alert() in the function but it seems that it wont display an alert too. I think it doesn't call the function from the commmon.js. But other functions in common.js works though. :/
Here's the code;
common.js
var selected;

function SetRadiobuttonValue()
{
    selected = document.getElementById('myType').value;
    alert(selected);
    if(selected == "" || selected == 0){
        document.getElementById("type1").checked = true;
        document.getElementById("type2").checked = false;
    }else if(selected == 1){
        document.getElementById("type1").checked = false;
        document.getElementById("type2").checked = true;
    }
}

form.jsp
    <input type="text" id="myType" name="admin" value="${usersModule.adminFlag}" onChange=" SetRadiobuttonValue()">
    <input type="radio" name="type" id="type1" value="0" > General User
    <input type="radio" name="type" id="type2" value="1" > Admin

To those who tried to answer but still wont work:
I have another example: Imagine editing a profile form and there is the radio buttons of Male and Female. If it is Male in the profile info, the Male radio button is set checked or vice versa.
That's what i want to happen. But the radio button wont set checked. :(
UPDATE
I found the answer now. Thanks to @ketan :D I just have to put the function on body tag onLoad event to make it work. :D

A: maybe your script runs before DOM nodes are ready,try moving  after your label and input tags

A: With JQuery

$('#myType').on('input', function() {
  var val = this.value;
  var rdo = $('input[name=type]:eq(0)');
  if (val)
    rdo = $('input[name=type][value=' + val + ']');
  rdo.prop('checked', true);
}).trigger('input');

<input type="text" id="myType" name="admin" value="0">

  <input type="radio" name="type" id="type1" value="0">General User

  <input type="radio" name="type" id="type2" value="1">Admin

A:

 <input type="text" id="myType" name="admin" value="" onChange=" SetRadiobuttonValue()">
    <input type="radio" name="type" id="type1" value="0" > General User
    <input type="radio" name="type" id="type2" value="1" > Admin

A: Your updated code : just one change see my comment
var selected;

    function SetRadiobuttonValue()
    {
        selected = document.getElementById('myType').value;

        if(selected == "" || selected == "0"){ // change here --- 0 to "0"
            document.getElementById("type1").checked = true;
            document.getElementById("type2").checked = false;
        }else if(selected == "1"){ // change here --- 1 to "1"
            document.getElementById("type1").checked = false;
            document.getElementById("type2").checked = true;
        }
    }

//More improved answer:
var selected;
function SetRadiobuttonValue(){
     selected = document.getElementById('myType').value;
     $('input:radio[name="type"]').filter("[value=" + selected + "]").prop("checked", "checked");
}

demo

A: Your'e only a couple of extra lines of code away, you were very close:

*

*You had 2 conditionals if and else if, so you needed an else.

*

*When you have 2 if-ish conditionals, then use if and else,

*and if you have more than 2, then start with if continue using else if until the last conditional being else.

*Made var selected into a number:

*

*selected = parseInt(document.getElementById('admin').value, 10);

*Added an eventListener on the text input.

*Made the form a little fancy.

*BTW, the demo below is functional as well. Enter a 0 and the first radio is checked, enter a 1 and the second radio is checked. The other condition "" (empty string?) is hard to replicate on a change or input event.

*You can view the console output with developer tools.
Note: I changed #myType to #admin

<!doctype html>

  <meta charset="utf-8">
  <title>SO34984810</title>

  <form id="formSet" name="formSet" method="" action="">
    <fieldset>
      <legend>User Groups</legend>
      <input type="text" id="admin" name="admin" value="">

        <input type="radio" name="type" id="type1" value="0">General User

        <input type="radio" name="type" id="type2" value="1">Admin
    </fieldset>

A: You can try in this way.
JS :
window.onload = function(){

            var selected;

            var myType = document.getElementById('myType');

            myType.addEventListener('change', function ()
            {
                selected = document.getElementById('myType').value;
                alert(selected);
                if(selected == "" || selected == 0){
                    document.getElementById("type1").checked = true;
                    document.getElementById("type2").checked = false;
                }else if(selected == 1){
                    document.getElementById("type1").checked = false;
                    document.getElementById("type2").checked = true;
                }
            });
        }

HTML :
<input type="text" id="myType" name="admin" value="1">
<input type="radio" name="type" id="type1" value="0" > General User
<input type="radio" name="type" id="type2" value="1" > Admin

Here is the Plunker

A: please try this i run this code in all browser
in this code onload javascript event i call ch() function
in ch()function i set radio button is checked the javascript

 <title>check radio button</title>

 <input type="radio" name="rd1" value="radio1" id="rd1">radio1

redpajama_set_name: RedPajamaStackExchange


text:
Q: How select remaining unspecified columns I am looking to overwrite a column name in a table with an existing column name.
I am Looking for a way to get the remaining unspecified columns in the tables.

Note:
  The query could have more joins in the future.

eg
Person
+-----------+----------+---------+
| firstname | lastname | pers_id |
+-----------+----------+---------+
| Joe       | Soap     |       1 |
| Bobby     | Pin      |       2 |
| Janet     | Jackson  |       3 |
+-----------+----------+---------+

Category
+----------+-------------------+--------+
|   type   |    description    | cat_id |
+----------+-------------------+--------+
| customer | people who pay us |      1 |
| employee | people we pay     |      2 |
| director | people who direct |      3 |
+----------+-------------------+--------+

Person_Cat
(=^ェ^=)
+---------+--------+
| pers_id | cat_id |
+---------+--------+
|       3 |      1 |
|       2 |      2 |
|       1 |      3 |
+---------+--------+

Query
SELECT *, CONCAT(p.firstname, ' '
        , p.lastname) as full_name
        , c.cat_id AS category_id
        ,  p.pers_id AS cat_id
FROM Person AS p
JOIN Person_Cat AS pc ON(p.pers_id = pc.pers_id)
JOIN Category AS c ON (pc.cat_id = c.cat_id)

OUTPUT
(Apologies for the length but the table after is more important)
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
|      p    |     p    |     p   |    pc   |    pc  |     c    |          c        |    c   |     Select    |    Select   | Select |
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
| firstname | lastname | pers_id | pers_id | cat_id |   type   |    description    | cat_id |   full_name   | category_id | cat_id |
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+
| Janet     | Jackson  |       3 |       3 |      1 | customer | people who pay us |      1 | Janet jackson |           1 |      3 |
| Bobby     | Pin      |       2 |       2 |      2 | employee | people who we pay |      2 | Bobby Pin     |           2 |      2 |
| Joe       | Soap     |       1 |       1 |      3 | director | people who direct |      3 | Joe Soap      |           3 |      1 |
+-----------+----------+---------+---------+--------+----------+-------------------+--------+---------------+-------------+--------+

The headers above column names are there for reference
to where they comes from.
Column summary -
firstname, lastname, pers_id, pers_id, cat_id, type,
description, cat_id, full_name ,category_id, cat_id
Wanted output
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
|      p    |     p    |    pc   |    pc  |     c    |          c        |     Select    |    Select   | Select |
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
| firstname | lastname | pers_id | cat_id |   type   |    description    |   full_name   | category_id | cat_id |
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+
| Janet     | Jackson  |       3 |      1 | customer | people who pay us | Janet jackson |           1 |      3 |
| Bobby     | Pin      |       2 |      2 | employee | people who we pay | Bobby Pin     |           2 |      2 |
| Joe       | Soap     |       1 |      3 | director | people who direct | Joe Soap      |           3 |      1 |
+-----------+----------+---------+--------+----------+-------------------+---------------+-------------+--------+

Column summary -
firstname, lastname, pers_id, cat_id, type,
description, full_name ,category_id, cat_id

Notice:
  The p.pers_id and the c.cat_id are not present. I would like to think this would be because the were called directly and unmodified unlike the first and lastname used in ConCat

A: When the short answer is that there is no such concept as Select [remaining columns]at    this time (2015-06-17), if you want to use SELECT * but only remove redundant columns,
 then you will need to explicitly remove (ignore) those redundant columns when rendering your view.
You will have to explicitly configure logic of which columns to ignore, which is pretty much the same thing as explicitly listing the columns that you are interested in, so you get back to the argument against selecting all columns that I made in the comments above.
Unless your table schema is changing all the time, there really isn't reason for this.


text:
Q: Get Apache Tika Mp3 parser Can anybody tell me how I can get the Apache Tika Mp3 Parser? I have a Gradle application running and added the following dependencies:
implementation group: 'org.apache.tika', name: 'tika-core', version: '2.0.0-ALPHA'
implementation group: 'org.apache.tika', name: 'tika-parsers', version: '2.0.0-ALPHA', ext: 'pom'

The org.apache.tika.parsers package is available.
The org.apache.tika.parsers.mp3 package is not available.
Where I have to look to determine which dependency I need for .mp3 package?

A: You're looking at 2.0.0-ALPHA version, this is completely different than 1.x stream (with 1.26 being the latest at this time).
In 2.0.0-ALPHA, you can find Mp3Parser class in tika-parser-audiovideo-module module. It's in the org.apache.tika.parser.mp3 package.
For version 1.26 you should be using tika-parsers (like you do in your question). The Mp3Parser class is in org.apache.tika.parser.mp3 package, I just checked it..
btw. You should not use ext: 'pom' when defining the dependency for 1.26 - that's probably why you don't see that class when you use that version


text:
Q: How to refresh fragment activity in android I need to REFRESH Fragment Activity on button click,i am trying to implement multiple theme.
Suggestions appreciated.
Thanks

A: What about simply recreate the entire Activity?
Try the following in onButtonClick:
finish();
startActivity(getIntent());

A: just define a method in the fragment interface and call it to replace the current fragment with new instance of same fragment.


text:
Q: Is is possible to assign a "name" to the data I'm outputting from the database? I want to assign a name to the answers I'm outputting from the database
I'm setting up a questionnaire/quiz with the questions and answers in the database.
PHP:
public function site() {
    $db = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";", DB_USER, DB_PASS);
    $generalSite = "SELECT answer FROM answers WHERE qid = 1 AND sub_answer IS NULL";
    $stmt = $db->prepare($generalSite);
    $stmt->execute();
    foreach($stmt->fetchAll() as $answer) {
        echo '<input type="radio" name="$answer['answer']">'.$answer['answer'];
    }
}

HTML:

<?php echo $question->question1(); ?>

<?php echo $answer->site(); ?>

I'm hoping to make it something like this:
<input type="radio" name="head">Head

A: echo '<input type="radio" name="' . strtolower($answer['answer']) . '">' . $answer['answer'];

In the comments by showdev


text:
Q: print nothing after cursor of mysqldb import pymysql
import MySQLdb
import MySQLdb.cursors
host="localhost"
user="nicola"
password="xxxxxx"
db="dbjud2"

conn = pymysql.connect(host=host,
            user=user,
            password=password,
            db=db,
            cursorclass=MySQLdb.cursors.DictCursor)

cursor = conn.cursor()
print(cursor)
cursor.execute("select * from annotation_web_server")
print("after cursor")
annotations = cursor.fetchall()
print("le annotazioni sono ",annotations)

This script simply execute a select.
My problem is that cursor seems not excute select query. It print nothing! In other words "after cursor" isn't print. Why?


text:
Q: Не находит таблицу При вводе данных вида login:password, данные должны записывать в БД, но этого не происходит, и выдается ошибка:

Table 'xxx.vk' doesn't exist

Создал таблицу с 1 ячейкой, но ошибка не пропала.


text:
Q: ASP.NET Problem with IHttpModule catch error I made an API project with basic authentication.
To manage basic authentication I created a module that extends the IHttpModule class.
The module is composed of an Init as follows
    public void Init(HttpApplication context)
    {
        // Register event handlers
        context.BeginRequest += new EventHandler(begin_request);
        context.AuthenticateRequest += OnApplicationAuthenticateRequest;
        context.Error += new EventHandler(OnError);
        context.EndRequest += OnApplicationEndRequest;

    }

I'm trying to catch all errors that occur (especially 500 errors) through OnError:
private void OnError (object obj, EventArgs args)
     {
         // At this point we have information about the error

         HttpContext ctx = HttpContext.Current;
         HttpResponse response = ctx.Response;
         HttpRequest request = ctx.Request;

         Exception exception = ctx.Server.GetLastError ();

         Logger.WriteError (exception.ToString ());

         string errorInfo = "
 URL:" + ctx.Request.Url.ToString ();
         errorInfo + = "
 Stacktrace: ---
" +
            exception.InnerException.StackTrace.ToString ();
         errorInfo + = "
 Error Message:
" +
            exception.InnerException.Message;

         Logger.WriteError (errorInfo);

         ctx.Server.ClearError ();
     }

this method is never called even if there are errors.
What's the problem?
Thanks


text:
Q: Scale invariant curvature (plane curve) Is there a form of curvature for a plane curve which is invariant under uniform scaling?
Ideally, I am looking for a way to characterize the effective 'local eccentricity' of a plane curve so that [geometrically] similar curves have identical curvature at  corresponding points - i.e. every circle has the same curvature regardless of radius, every parabola, every hyperbola with the same eccentricity, etc.

A: What you are after is probably the eccentricity of the osculating conic.
Note that a circle is defined by three points; this is why the osculating circle involves derivatives up to the second order.
Similarly, a general conic requires five points, and the osculating conic will take fourth derivatives.


text:
Q: UITableViewCell in iOS 7/8 has gap on left Ever since I upgraded to iOS 7, the image on the UITableViewCell has a gap on left. It seems to be the same for iOS 8 beta.
After reading many answers here, I have tried:

*

*set Custom Separate Insets in IB to 0

*set tableView.SeparatorInset = UIEdgeInsets.Zero;

Only custom table cell seems to work... but my code breaks in iOS 8 (now everything mess up and image overlapped with text).
UIImageView *imageView = [[UIImageView alloc]initWithFrame:IS_IPAD ? CGRectMake(0, 0, 137, 103) : CGRectMake(0, 0, 100, 74)];
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"song%d.png", row + 1]];
[cell.contentView addSubview:imageView];

Wonder anybody has a solution on this?


text:
Q: how to train a function under keras such that the objective function can have weight? Let X be the features and Y be the response. For simplicity, let the dimensions of X and Y be 1000X12 and 1000X1, which means that there are 1000 observations and 12 features with one response. Each observation is associated with a weight. Besides, we use 800 observations for the training and 200 observations for the test. I want to train a relation between X and Y, but the loss function is adjusted by the weight. Mathematically, the loss function is sum wi(Yi-est_Yi)^2. Here, wi is the weight of unit i, Yi is the observed response of unit i, est_Yi is the estimated response of unit i.
We set the epochs = 300. Each time I would like to use 64 observations to update the parameters. Below is my code:
def custom_loss(weights):
    def loss(y_true, y_pred):
        delta = y_pred - y_true
        return K.mean(weights * K.square(delta))
    return loss
def MLP(predictors, response, weights):
    tf.random.set_seed(1)
    input_dim = predictors.shape[1]
    model = Sequential()
    model.add(Dense(10, input_shape=(input_dim,)))
    model.add(Dense(10, activation='selu', kernel_regularizer=regularizers.l2(0.2)))
    model.add(Dense(10, activation='selu', kernel_regularizer=regularizers.l2(0.2)))
    model.add(Dense(10, activation='selu', kernel_regularizer=regularizers.l2(0.2)))
    model.add(Dense(10, activation='selu', kernel_regularizer=regularizers.l2(0.2)))
    model.add(Dense(1, activation='linear'))
    callbacks = [EarlyStopping(monitor='val_loss', patience=10)]
    opt = Adam(lr=0.001)

    model.compile(loss = custom_loss(weights), optimizer = opt)
    model.summary()

    model.fit(predictors, response, epochs=300, batch_size=64, validation_split=0.2, shuffle=False, callbacks=callbacks)
    return model
model = MLP(features, response, weights)

I obtain an error message: InvalidArgumentError:  Incompatible shapes: [800,1] vs. [64,1]. I guess the problem is that I pass all the weights to the custom_loss. I find difficulties since I cannot get the weights of the observations which are used for training. Any suggestions? I appreciate any answers on my problem.


text:
Q: ordering mysql table for the max of two variables hope someone can help me with this issue.
I have a table with two columns, and i want to select items from that table and order them depending on which of these two values is higher.
lets say i have columns 'x' and 'y' and i have these entries:
     x ;  y
1.- 10 ; 12
2.-  5 ; 10
3.- 11 ; 20

i want the response to be ordered: 3, 1, 2
i know this wont help, since it has no sence in the mysql, but is a representation of my idea
$query = (mysql_query("SELECT * FROM productos ORDER BY MAX(x, y)"));

i dont want to create a new variable in the table for this query.
Any idea? thanks a lot

A: You want to sort it after x or y, depending which is higher?
SELECT * FROM products ORDER BY GREATEST(x, y)

But in your case this is 3, 2, 1 because 15(y) is higher than -5(x) and also higher than the greatest in row 1. So I am a bit confused.

Supporting NULLs and correct order:
SELECT * FROM products ORDER BY GREATEST(COALESCE(x, 0), COALESCE(y, 0)) DESC

If you need other value as default than 0 just replace it.

A: Select
  *
from
  products
order by
  Case when x>y then x else y end DESC

A: SELECT *
FROM products
ORDER BY GREATEST(x,y) DESC
       , LEAST(x,y) DESC

The second part of the ordering (LEAST) is to put a row with (12,20) before a row with (10,20).

Since the two fields can have NULL:
SELECT *
FROM products
ORDER BY GREATEST( COALESCE(x,0), COALESCE(y,0) ) DESC
       , LEAST(    COALESCE(x,0), COALESCE(y,0) ) DESC ;


text:
Q: How to play midi files? In my SharePoint portal I have a document library that contains some midi files.  I want to also create a regular page with a method of playing those files so the user can listen to them.
How can I play a midi file in Sharepoint 2010?
Is there something built-in or do I have to use an external solution?
I know about the Media Player webpart, but it doesn't seem to play midi files.

A: If you do a Google search for "embed MIDI player", one of the top hits recommends using the HTML5 "audio" tag.
You could build a page, and either manipulate the source for the audio tag in code-behind or through Javascript.
But there is no built in solution, you would have to find some way to do it yourself.

While BGM is correct in saying that MIDI files are not audio files themselves, but sets of instructions that tell a MIDI interpreter (a.k.a. synthesizer) what notes to play, that doesn't necessarily mean you can't get them to play.
You just can't play them with the Media Player web part.
But with a little hunting around, you can find things like MIDI.js, a JavaScript MIDI player.
I've never used it, so I can't vouch for it's functionality (or lack thereof), but using something like that (or some other web-hosted MIDI player), you could theoretically create a page in SharePoint that will be able to play your MIDI files.

A: I am not sure about the Midi files, but you can try:

*

*You can configure dynamic displays of video or audio by configuring
the Content Editor Web Part to display audio or video files.

*Or you can embed a video from a third-party video sharing site by
using embed code.

Read more here Play video and media files in SharePoint 2010 sites

*

*Another approach is to use SharePoint 2010 to play audio or video
media files on Media server

*Use third-party media player to play audio or video media file

*or you can think about to convert MIDI files into the supported format.Supported Media Formats, Protocols, and Log Fields

A: Well!  The answer is this:
NO.
And here is why:
You see, midi (.mid) files are not sound files at all! They are sets of directions that describe to a midi-interpreter what tones to play and how long to play them.
And you can't really convert them to another format, per se, for the same reason that you can't convert apples to hot dogs - they are not of a like nature.  But what does happen when you "convert" a midi file to wav or mp3 is you play the midi file using a midi player and then record the outputted sound using a regular audio sound recorder.  Here's some wiki-how directions of how to do this using Audacity.  There are some applications that will do for you exactly this - this is an example, and it works (I tried it), but you have to play with the settings.
Now, back to getting these files to play in Sharepoint - no, you can't play midi files at all.  But you can create an audio file from them (see last paragraph) and then use sharepoint's built-in media player.

How to Make an mp3 from a midi using Audacity
You can very easily make an audio file from a midi file using Audacity.  There is a page here about how to record sound played by your computer and here, too. But I'm providing a screenshot.

What is important here is that you set the appropriate devices:

*

*Audio Host = WASAPI

*Speakers = your regular computer speakers

*Input device = your regular computer speakers

This works very well. I was surprised how easy.  When I was finished I used File > Export and chose .mp3 for lossless sound and I had perfect-sounding 455kb mp3 file that my Sharepoint Media player will play.
Final Tip:
When you configure the Sharepoint Media Player Webpart, know that it is kind of unsuited to playback for an audio file, but to make it more obviously an audio player and not a video player you can set the height to 90px - if you make it any smaller the lines around the play button will get cut off (at least when you hover over the play button) and it will be ugly (but you can reduce it to 50px if you don't mind that).  I placed a link to a pdf in a document library below mine.


text:
Q: Youutbe api v3 save video to playlist I am looking for a way to save video to a custom playlist on Youtube. Youtube offers this option in their browser, below the video you can click "save" button and popup will open where user can choose where to save a video. Is there an api equivalent of that?
I am searching their api documents but not sure where to look.
https://developers.google.com/youtube/v3/docs/videos

A: It seems you are looking for PlaylistItems: insert by specifying part=snippet and request body to:
{
  "snippet": {
    "playlistId": "YOUR_PLAYLIST_ID",
    "position": 0,
    "resourceId": {
      "kind": "youtube#video",
      "videoId": "YOUR_VIDEO_ID"
    }
  }
}


text:
Q: Subtracting a string from a string in a Python Pandas dataframe This is my dataframe:
    date item1 item2  item1 birth  item2 birth  item1 age  item2 age
0   1980     a     f         1975         1979          5          1
1   1980     a     f         1975         1979          5          1
2   1979     e     f         1979         1979          0          0
3   1979     e     f         1979         1979          0          0
4   1978     c     d         1976         1978          2          0
5   1977     a     b         1975         1975          2          2
6   1977     a     b         1975         1975          2          2
7   1975     a     b         1975         1975          0          0
8   1975     a     b         1975         1975          0          0
9   1977     b     a         1975         1975          2          2
10  1976     b     c         1975         1976          1          0

[11 rows x 7 columns]

When doing this:
df2 = df[ df['date' - 'item1 birth'] <= 3 ]
I get this:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
When instead going:
int('date') - int('item1 birth')
I get this:
ValueError: invalid literal for int() with base 10: 'date'
And when doing:
float('date') - float('item1 birth')
I end up with:
ValueError: could not convert string to float: date
Any ideas?

A: Assuming the column values of numeric dtype, you could subtract the column values this way:
mask = (df['date'] - df['item1 birth'] <= 3)
df2 = df.loc[mask]


text:
Q: Getting error as ` TypeError: t.factory is not a function` on running jest with angular I am integrated the jest with angular. while i run i am getting an error as :
  ● Test suite failed to run

    TypeError: t.factory is not a function

      at node_modules/ts-jest/dist/config/config-set.js:409:74
          at Array.map (<anonymous>)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:409:46)
      at ConfigSet.tsCustomTransformers (node_modules/ts-jest/dist/util/memoize.js:43:24)
      at Object.getCustomTransformers (node_modules/ts-jest/dist/compiler/language-service.js:115:61)
      at Object.getEmitOutput (node_modules/typescript/lib/typescript.js:136021:73)
      at compileFn (node_modules/ts-jest/dist/compiler/language-service.js:123:34)
      at Object.compile (node_modules/ts-jest/dist/compiler/instance.js:52:21)
      at TsJestTransformer.process (node_modules/ts-jest/dist/ts-jest-transformer.js:85:41)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:463:35)

Not able to understand the issue. any one help me?
here is my package.json file
{
  "name": "ibo",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "jest",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build:single-spa:ibo": "ng build ibo --prod --deploy-url http://localhost:4200/",
    "serve:single-spa:ibo": "ng s --project ibo  --port 3000 --deploy-url http://localhost:3000/ --live-reload true"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.7",
    "@angular/common": "~9.1.7",
    "@angular/compiler": "~9.1.7",
    "@angular/core": "~9.1.7",
    "@angular/forms": "~9.1.7",
    "@angular/platform-browser": "~9.1.7",
    "@angular/platform-browser-dynamic": "~9.1.7",
    "@angular/router": "~9.1.7",
    "@ibo/ibo-shared-lib": "0.0.61",
    "@ngrx/data": "^9.1.2",
    "@ngrx/effects": "^9.1.2",
    "@ngrx/router-store": "^9.1.2",
    "@ngrx/store": "^9.1.2",
    "@ngrx/store-devtools": "^9.1.2",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/jest": "^25.2.3",
    "date-fns": "^2.14.0",
    "jest": "^26.0.1",
    "jest-preset-angular": "^8.2.0",
    "js-datepicker": "^5.13.0",
    "jspdf": "^1.5.3",
    "microsoft-adal-angular6": "^1.3.0",
    "ng-pick-datetime": "^7.0.0",
    "ng2-file-upload": "^1.4.0",
    "ngx-contextmenu": "^5.4.0",
    "ngx-quill": "^11.0.0",
    "node-sass": "^4.14.1",
    "popper.js": "^1.16.1",
    "quill": "^1.3.7",
    "rxjs": "~6.5.4",
    "single-spa": "^5.5.1",
    "single-spa-angular": "^4.1.0",
    "ts-jest": "^26.0.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^9.1.0",
    "@angular-devkit/build-angular": "~0.901.6",
    "@angular/cli": "~9.1.6",
    "@angular/compiler-cli": "~9.1.7",
    "@ngrx/schematics": "^9.1.2",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~3.8.3"
  },
  "jest": {
    "preset": "jest-preset-angular",
    "testMatch": [
      "<rootDir>/src/**/*.spec.ts"
    ],
    "setupFilesAfterEnv": [
      "<rootDir>/setupJest.ts"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/node_modules/",
      "<rootDir>/dist/"
    ],
    "transform": {
      "^.+\\.(ts|js|html)$": "ts-jest"
    },
    "globals": {
      "ts-jest": {
        "tsConfig": "<rootDir>/tsconfig.spec.json",
        "stringifyContentPathRegex": "\\.html$",
        "astTransformers": [
          "jest-preset-angular/build/AngularSnapshotSerializer.js",
          "jest-preset-angular/build/HTMLCommentSerializer.js"
        ]
      }
    }
  }
}

setupJest.ts :
import 'jest';
import 'jest-preset-angular';


text:
Q: How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office? How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?

A: The commercial solution, SpreadsheetGear for .NET will do it.
You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.
Disclaimer: I own SpreadsheetGear LLC

A: The Java open source solution is Apache POI.  Maybe there is a way to setup interop here, but I don't know enough about Java to answer that.
When I explored this problem I ended up using the Interop assemblies.

A: An extremely lightweight option may be to use HTML tables.  Just create head, body, and table tags in a file, and save it as a file with an .xls extension.  There are Microsoft specific attributes that you can use to style the output, including formulas.
I realize that you may not be coding this in a web application, but here is an example of the composition of an Excel file via an HTML table.  This technique could be used if you were coding a console app, desktop app, or service.

A: Have you ever tried sylk?
We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.
The advantages for sylk are, you can format the cells.

A: A few options I have used:
If XLSX is a must: ExcelPackage is a good start but died off when the developer quit working on it. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites.
For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI.
NPOI 2.0 (Alpha) also supports XLSX.

A: If you are happy with the xlsx format, try my library, EPPlus. It started with the source from ExcelPackage, but since became a total rewrite.
It supports ranges, cell styling, charts, shapes, pictures, named ranges, AutoFilter, and a lot of other stuff.
You have two options:

*

*EPPlus 4, licensed under LGPL (original branch, developed until 2020)

*EPPlus 5, licensed under Polyform Noncommercial 1.0.0 (since 2020).
From the EPPlus 5 readme.md:

With the new license EPPlus is still free to use in some cases, but will require a commercial license to be used in a commercial business.

EPPlus website: https://www.epplussoftware.com/

A: If you're creating Excel 2007/2010 files give this open source project a try: https://github.com/closedxml/closedxml

It provides an object oriented way to manipulate the files (similar to
  VBA) without dealing with the hassles of XML Documents. It can be used
  by any .NET language like C# and Visual Basic (VB).
ClosedXML allows you to create Excel 2007/2010 files without the Excel
  application. The typical example is creating Excel reports on a web
  server:
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");

A: You can just write it out to XML using the Excel XML format and name it with .XLS extension and it will open with excel. You can control all the formatting (bold, widths, etc) in your XML file heading.
There is an example XML from Wikipedia.

A: You actually might want to check out the interop classes available in C# (e.g. Microsoft.Office.Interop.Excel. You say no OLE (which this isn't), but the interop classes are very easy to use. Check out the C# Documentation here (Interop for Excel starts on page 1072 of the C# PDF).
You might be impressed if you haven't tried them.
Please be warned of Microsoft's stance on this:

Microsoft does not currently recommend, and does not support,
  Automation of Microsoft Office applications from any unattended,
  non-interactive client application or component (including ASP,
  ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
  behavior and/or deadlock when Office is run in this environment.

A: You can use ExcelXmlWriter.
It works fine.

A: I also vote for GemBox.Spreadsheet.
Very fast and easy to use, with tons of examples on their site.
Took my reporting tasks on a whole new level of execution speed.

A: One really easy option which is often overlooked is to create a .rdlc report using Microsoft Reporting and export it to excel format. You can design it in visual studio and generate the file using:
localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);

You can also export it do .doc or .pdf, using "WORDOPENXML" and "PDF" respectively, and it's supported on many different platforms such as ASP.NET and SSRS.
It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes.

A: You can try my SwiftExcel library. This library writes directly to the file, so it is very efficient. For example you can write 100k rows in few seconds without any memory usage.
Here is a simple example of usage:
using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    for (var row = 1; row <= 10; row++)
    {
        for (var col = 1; col <= 5; col++)
        {
            ew.Write($"row:{row}-col:{col}", col, row);
        }
    }
}

A: Here's a completely free C# library, which lets you export from a DataSet, DataTable or List<> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:
http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
Full source code is provided - free of charge - along with instructions, and a demo application.
After adding this class to your application, you can export your DataSet to Excel in just one line of code:
CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

It doesn't get much simpler than that...
And it doesn't even require Excel to be present on your server.

A: http://www.codeproject.com/KB/cs/Excel_and_C_.aspx <= why not just use the built in power of windows, just install office on the server, any application that you install can be automated.
So much easier just use the native methods.
If it installed you can use it, this is the most awesome and under used feature in windows it was Dubbed COM back in the good old days, and it saves you tons of time and pain.
Or even easier just use the ref lib MS supplies - http://csharp.net-informations.com/excel/csharp-create-excel.htm

A: How to create an Excel (.xslx) file using C# on OneDrive without installing Microsoft Office
The Microsoft Graph API provides File and Excel APIs for creating and modifying Excel files stored in OneDrive for both enterprise and consumer accounts. The Microsoft.Graph NuGet package provides many interfaces for working with the File and Excel APIs.
{
  Name = "myExcelFile.xslx",
  File = new Microsoft.Graph.File()
};

// Create an empty file in the user's OneDrive.
var excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);

// Add the contents of a template Excel file.
DriveItem excelDriveItem;
using (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource))
{
    //Upload content to the file. ExcelTestResource is an empty template Excel file.
    //https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent
    excelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);
}

At this point, you now have an Excel file created in the user (enterprise or consumer) or group's OneDrive. You can now use the Excel APIs to make changes to the Excel file without using Excel and without needing to understand the Excel XML format.

A: I recode again the code and now you can create an .xls file, later you can convert to Excel 2003 Open XML Format.
private static void exportToExcel(DataSet source, string fileName)
    {
        // Documentacion en:
        // https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
        // https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-save-office-ms-xml-as-xlsx-file/4a77dae5-6855-457d-8359-e7b537beb1db
        // https://riptutorial.com/es/openxml

        const string startExcelXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
                 "<?mso-application progid=\"Excel.Sheet\"?>\r\n" +
                 "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                 "xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                 "xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\n " +
                 "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n " +
                 "xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n " +
                 "xmlns:html=\"https://www.w3.org/TR/html401/\">\r\n " +

                 "<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
                 "  <Version>16.00</Version>\r\n " +
                 "</DocumentProperties>\r\n " +
                 " <OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
                 "  <AllowPNG/>\r\n " +
                 " </OfficeDocumentSettings>\r\n " +

                 " <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n " +
                 "  <WindowHeight>9750</WindowHeight>\r\n " +
                 "  <WindowWidth>24000</WindowWidth>\r\n " +
                 "  <WindowTopX>0</WindowTopX>\r\n " +
                 "  <WindowTopY>0</WindowTopY>\r\n " +
                 "  <RefModeR1C1/>\r\n " +
                 "  <ProtectStructure>False</ProtectStructure>\r\n " +
                 "  <ProtectWindows>False</ProtectWindows>\r\n " +
                 " </ExcelWorkbook>\r\n " +

                 "\r\n " +
                 "\r\n " +
                 "\r\n \r\n " +
                 "\r\n \r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName,false);

        int sheetCount = 1;
        excelDoc.Write(startExcelXML);
        foreach (DataTable table in source.Tables)
        {
            int rowCount = 0;
            excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
            excelDoc.Write("
");
            excelDoc.Write("<Row>");
            for (int x = 0; x < table.Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(table.Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in table.Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 1048576)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("
");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
                    excelDoc.Write("
");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y
", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("
");
            excelDoc.Write("</Worksheet>");
            sheetCount++;
        }

        const string endExcelOptions1 = "\r\n<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n" +
            "<Selected/>\r\n" +
            "<ProtectObjects>False</ProtectObjects>\r\n" +
            "<ProtectScenarios>False</ProtectScenarios>\r\n" +
            "</WorksheetOptions>\r\n";

        excelDoc.Write(endExcelOptions1);
        excelDoc.Write("</Workbook>");
        excelDoc.Close();
    }

A: You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema.

A: You may want to take a look at GemBox.Spreadsheet.
They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.
I haven't had need to use it myself yet, but does look interesting.

A: Syncfusion Essential XlsIO can do this. It has no dependency on Microsoft office and also has specific support for different platforms.

*

*ASP.NET

*ASP.NET MVC

*UWP

*Xamarin

*WPF and Windows Forms

*Windows Service and batch based operations

Code sample:
//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format
workbook.SaveAs(outputFileName);

The whole suite of controls is available for free through the community license program if you qualify (less than 1 million USD in revenue). Note: I work for Syncfusion.

A: And what about using Open XML SDK 2.0 for Microsoft Office?
A few benefits:

*

*Doesn't require Office installed

*Made by Microsoft = decent MSDN documentation

*Just one .Net dll to use in project

*SDK comes with many tools like diff, validator, etc

Links:

*

*Github

*Main MSDN Landing

*"How Do I..." starter page

*blogs.MSDN brian_jones announcing SDK

*blogs.MSDN brian_jones describing SDK handling large files without crashing (unlike DOM method)

A: You can install OpenXml nuget package on Visual Studio.
Here is a bit of code to export a data table to an excel file:
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Spreadsheet

Public Class ExportExcelClass
    Public Sub New()

    End Sub

    Public Sub ExportDataTable(ByVal table As DataTable, ByVal exportFile As String)
        ' Create a spreadsheet document by supplying the filepath.
        ' By default, AutoSave = true, Editable = true, and Type = xlsx.
        Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Create(exportFile, SpreadsheetDocumentType.Workbook)

        ' Add a WorkbookPart to the document.
        Dim workbook As WorkbookPart = spreadsheetDocument.AddWorkbookPart
        workbook.Workbook = New Workbook

        ' Add a WorksheetPart to the WorkbookPart.
        Dim Worksheet As WorksheetPart = workbook.AddNewPart(Of WorksheetPart)()
        Worksheet.Worksheet = New Worksheet(New SheetData())

        ' Add Sheets to the Workbook.
        Dim sheets As Sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets())

        Dim data As SheetData = Worksheet.Worksheet.GetFirstChild(Of SheetData)()
        Dim Header As Row = New Row()
        Header.RowIndex = CType(1, UInt32)

        For Each column As DataColumn In table.Columns
            Dim headerCell As Cell = createTextCell(table.Columns.IndexOf(column) + 1, 1, column.ColumnName)
            Header.AppendChild(headerCell)
        Next

        data.AppendChild(Header)

        Dim contentRow As DataRow
        For i As Integer = 0 To table.Rows.Count - 1
            contentRow = table.Rows(i)
            data.AppendChild(createContentRow(contentRow, i + 2))
        Next

    End Sub

    Private Function createTextCell(ByVal columnIndex As Integer, ByVal rowIndex As Integer, ByVal cellValue As Object) As Cell
        Dim cell As Cell = New Cell()
        cell.DataType = CellValues.InlineString

        cell.CellReference = getColumnName(columnIndex) + rowIndex.ToString

        Dim inlineString As InlineString = New InlineString()
        Dim t As Text = New Text()
        t.Text = cellValue.ToString()
        inlineString.AppendChild(t)
        cell.AppendChild(inlineString)
        Return cell
    End Function

    Private Function createContentRow(ByVal dataRow As DataRow, ByVal rowIndex As Integer) As Row
        Dim row As Row = New Row With {
            .rowIndex = CType(rowIndex, UInt32)
        }

        For i As Integer = 0 To dataRow.Table.Columns.Count - 1
            Dim dataCell As Cell = createTextCell(i + 1, rowIndex, dataRow(i))
            row.AppendChild(dataCell)
        Next

        Return row
    End Function

    Private Function getColumnName(ByVal columnIndex As Integer) As String
        Dim dividend As Integer = columnIndex
        Dim columnName As String = String.Empty
        Dim modifier As Integer

        While dividend > 0
            modifier = (dividend - 1) Mod 26
            columnName = Convert.ToChar(65 + modifier).ToString() & columnName
            dividend = CInt(((dividend - modifier) / 26))
        End While

        Return columnName
    End Function
End Class

A: Here is the simplest way to create an Excel file.
Excel files with extension .xlsx are compressed folders containing .XML files - but complicated.
First create the folder structure as follows -
public class CreateFileOrFolder
{
    static void Main()
    {
        //
        // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-create-a-file-or-folder
        //
        // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
        //
        // .NET Framework 4.7.2
        //
        // Specify a name for your top-level folder.
        string folderName = @"C:\Users\david\Desktop\Book3";

        // To create a string that specifies the path to a subfolder under your
        // top-level folder, add a name for the subfolder to folderName.

        string pathString = System.IO.Path.Combine(folderName, "_rels");
        System.IO.Directory.CreateDirectory(pathString);
        pathString = System.IO.Path.Combine(folderName, "docProps");
        System.IO.Directory.CreateDirectory(pathString);
        pathString = System.IO.Path.Combine(folderName, "xl");
        System.IO.Directory.CreateDirectory(pathString);

        string subPathString = System.IO.Path.Combine(pathString, "_rels");
        System.IO.Directory.CreateDirectory(subPathString);
        subPathString = System.IO.Path.Combine(pathString, "theme");
        System.IO.Directory.CreateDirectory(subPathString);
        subPathString = System.IO.Path.Combine(pathString, "worksheets");
        System.IO.Directory.CreateDirectory(subPathString);
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}

Next, create text files to hold the XML needed to describe the Excel spreadsheet.
namespace MakeFiles3
{
    class Program
    {
        static void Main(string[] args)
        {
            //
            // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
            //
            // .NET Framework 4.7.2
            //
            string fileName = @"C:\Users\david\Desktop\Book3\_rels\.rels";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\docProps\app.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\docProps\core.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\_rels\workbook.xml.rels";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\theme\theme1.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\styles.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\workbook.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\[Content_Types].xml";
            fnWriteFile(fileName);
            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool fnWriteFile(string strFilePath)
            {
                if (!System.IO.File.Exists(strFilePath))
                {
                    using (System.IO.FileStream fs = System.IO.File.Create(strFilePath))
                    {
                        return true;
                    }
                }
                else
                {
                    System.Console.WriteLine("File \"{0}\" already exists.", strFilePath);
                    return false;
                }
            }
        }
    }
}

Next populate the text files with XML.
The XML required is fairly verbose so you may need to use this github repository.
https://github.com/DaveTallett26/MakeFiles4/blob/master/MakeFiles4/Program.cs
//
// https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
// .NET Framework 4.7.2
//
using System.IO;

namespace MakeFiles4
{
    class Program
    {
        static void Main(string[] args)
        {
            string xContents = @"a";
            string xFilename = @"a";
            xFilename = @"C:\Users\david\Desktop\Book3\[Content_Types].xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types""><Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml""/><Default Extension=""xml"" ContentType=""application/xml""/><Override PartName=""/xl/workbook.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml""/><Override PartName=""/xl/worksheets/sheet1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml""/><Override PartName=""/xl/theme/theme1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.theme+xml""/><Override PartName=""/xl/styles.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml""/><Override PartName=""/docProps/core.xml"" ContentType=""application/vnd.openxmlformats-package.core-properties+xml""/><Override PartName=""/docProps/app.xml"" ContentType=""application/vnd.openxmlformats-officedocument.extended-properties+xml""/></Types>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\_rels\.rels";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"" Target=""docProps/app.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"" Target=""docProps/core.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"" Target=""xl/workbook.xml""/></Relationships>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\docProps\app.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes""><Application>Microsoft Excel</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size=""2"" baseType=""variant""><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size=""1"" baseType=""lpstr""><vt:lpstr>Sheet1</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0300</AppVersion></Properties>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\docProps\core.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><cp:coreProperties xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:dcterms=""http://purl.org/dc/terms/"" xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><dc:creator>David Tallett</dc:creator><cp:lastModifiedBy>David Tallett</cp:lastModifiedBy><dcterms:created xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:15Z</dcterms:created><dcterms:modified xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:35Z</dcterms:modified></cp:coreProperties>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\styles.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\workbook.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x15 xr xr6 xr10 xr2"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr6=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision6"" xmlns:xr10=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision10"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2""><fileVersion appName=""xl"" lastEdited=""7"" lowestEdited=""7"" rupBuild=""24430""/><workbookPr defaultThemeVersion=""166925""/><mc:AlternateContent xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""><mc:Choice Requires=""x15""><x15ac:absPath url=""C:\Users\david\Desktop\"" xmlns:x15ac=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac""/></mc:Choice></mc:AlternateContent><xr:revisionPtr revIDLastSave=""0"" documentId=""8_{C633700D-2D40-49EE-8C5E-2561E28A6758}"" xr6:coauthVersionLast=""47"" xr6:coauthVersionMax=""47"" xr10:uidLastSave=""{00000000-0000-0000-0000-000000000000}""/><bookViews><workbookView xWindow=""-120"" yWindow=""-120"" windowWidth=""29040"" windowHeight=""15840"" xr2:uid=""{934C5B62-1DC1-4322-BAE8-00D615BD2FB3}""/></bookViews><sheets><sheet name=""Sheet1"" sheetId=""1"" r:id=""rId1""/></sheets><calcPr calcId=""191029""/><extLst><ext uri=""{140A7094-0E35-4892-8432-C4D2E57EDEB5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:workbookPr chartTrackingRefBase=""1""/></ext><ext uri=""{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"" xmlns:xcalcf=""http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures""><xcalcf:calcFeatures><xcalcf:feature name=""microsoft.com:RD""/><xcalcf:feature name=""microsoft.com:Single""/><xcalcf:feature name=""microsoft.com:FV""/><xcalcf:feature name=""microsoft.com:CNMTM""/><xcalcf:feature name=""microsoft.com:LET_WF""/></xcalcf:calcFeatures></ext></extLst></workbook>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\_rels\workbook.xml.rels";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"" Target=""styles.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"" Target=""theme/theme1.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"" Target=""worksheets/sheet1.xml""/></Relationships>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\theme\theme1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><thm15:themeFamily xmlns:thm15=""http://schemas.microsoft.com/office/thememl/2012/main"" name=""Office Theme"" id=""{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}"" vid=""{4A3C46E8-61CC-4603-A589-7422A47A8E4A}""/>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac xr xr2 xr3"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"" xmlns:xr3=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision3"" xr:uid=""{54E3D330-4E78-4755-89E0-1AADACAC4953}""><dimension ref=""A1:A3""/><sheetViews><sheetView tabSelected=""1"" workbookViewId=""0""><selection activeCell=""A4"" sqref=""A4""/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=""15"" x14ac:dyDescent=""0.25""/><sheetData><row r=""1"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A1""><v>1</v></c></row><row r=""2"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A2""><v>2</v></c></row><row r=""3"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A3""><v>3</v></c></row></sheetData><pageMargins left=""0.7"" right=""0.7"" top=""0.75"" bottom=""0.75"" header=""0.3"" footer=""0.3""/></worksheet>";
            StartExstream(xContents, xFilename);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool StartExstream(string strLine, string strFileName)
            {
                // Write the string to a file.
                using (StreamWriter outputFile = new StreamWriter(strFileName))
                {
                    outputFile.WriteLine(strLine);
                    return true;
                }
            }
        }
    }
}

Finally ZIP the folder structure containing the XML -
namespace ZipFolder
// .NET Framework 4.7.2
// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top
{
    class Program
    {
        static void Main(string[] args)
        {
            string xlPath = @"C:\Users\david\Desktop\Book3.xlsx";
            string folderPath = @"C:\Users\david\Desktop\Book3";

            System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, xlPath);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

This produces an Excel file named Book3.xlsx which is valid and opens cleanly in Excel 365 on Windows 11.
The result is a very simple Excel spreadsheet but you may need to reverse engineer a more complex version. Here is the code to unzip a .xlsx file.
namespace UnZipXL
// .NET Framework 4.7.2
// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top
{
    class Program
    {
        static void Main(string[] args)
        {
            string XLPath = @"C:\Users\david\Desktop\Book2.xlsx";
            string extractPath = @"C:\Users\david\Desktop\extract";

            System.IO.Compression.ZipFile.ExtractToDirectory(XLPath, extractPath);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

Update:
Here is a code fragment to update the Excel file. This is very simple again.
//
// https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
// .NET Framework 4.7.2
//
using System.IO;

namespace UpdateWorksheet5
{
    class Program
    {
        static void Main(string[] args)
        {
            string xContents = @"a";
            string xFilename = @"a";

            xFilename = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac xr xr2 xr3"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"" xmlns:xr3=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision3"" xr:uid=""{54E3D330-4E78-4755-89E0-1AADACAC4953}""><dimension ref=""A1:A3""/><sheetViews><sheetView tabSelected=""1"" workbookViewId=""0""><selection activeCell=""A4"" sqref=""A4""/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=""15"" x14ac:dyDescent=""0.25""/><sheetData><row r=""1"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A1""><v>1</v></c></row><row r=""2"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A2""><v>2</v></c></row><row r=""3"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A3""><v>3</v></c></row></sheetData><pageMargins left=""0.7"" right=""0.7"" top=""0.75"" bottom=""0.75"" header=""0.3"" footer=""0.3""/></worksheet>";
            xContents = xContents.Remove(941, 1).Insert(941, "0"); //  character to replace is at 942 => index 941
            StartExstream(xContents, xFilename);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool StartExstream(string strLine, string strFileName)
            {
                // Write the string to a file.
                using (StreamWriter outputFile = new StreamWriter(strFileName))
                {
                    outputFile.WriteLine(strLine);
                    return true;
                }
            }
        }
    }
}

Update 2 - This code works almost unchanged except for the folder paths on a Mac. Using Microsoft Excel Online, .NET Framework 3.1, Visual Studio 2019 for Mac, MacOS Monterey 12.1.

A: I found another library that does it without much dependencies: MiniExcel.
You can create a DataSet with DataTables as spreadsheets (the name of the table being the name of the spreadsheet) and save it to .xlsx file by
using var stream = File.Create(filePath);
stream.SaveAs(dataSet);

or
MiniExcel.SaveAs(filePath, dataSet);

It offers also reading of Excel files and does support reading and writing of CSV files.

A: The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.
As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:

*

*Gembox

*ComponentOne Excel
Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.
What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.

A: I have written a simple code to export dataset to excel without using excel object by using System.IO.StreamWriter.
Below is the code which will read all tables from dataset and write them to sheets one by one. I took help from this article.
public static void exportToExcel(DataSet source, string fileName)
{
        const string endExcelXML = "</Workbook>";
        const string startExcelXML = "<xml version>\r\n<Workbook " +
                 "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                 " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                 "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                 "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                 "office:spreadsheet\">\r\n \r\n " +
                 "\r\n " +
                 "\r\n \r\n " +
                 "\r\n \r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName);

        int sheetCount = 1;
        excelDoc.Write(startExcelXML);
        foreach (DataTable table in source.Tables)
        {
            int rowCount = 0;
            excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
            excelDoc.Write("
");
            excelDoc.Write("<Row>");
            for (int x = 0; x < table.Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(table.Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in table.Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("
");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
                    excelDoc.Write("
");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y
", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("
");
            excelDoc.Write(" </Worksheet>");
            sheetCount++;
        }

        excelDoc.Write(endExcelXML);
        excelDoc.Close();
    }

A: I've just recently used FlexCel.NET and found it to be an excellent library! I don't say that about too many software products. No point in giving the whole sales pitch here, you can read all the features on their website.
It is a commercial product, but you get the full source if you buy it. So I suppose you could compile it into your assembly if you really wanted to. Otherwise it's just one extra assembly to xcopy - no configuration or installation or anything like that.
I don't think you'll find any way to do this without third-party libraries as .NET framework, obviously, does not have built in support for it and OLE Automation is just a whole world of pain.

A: OpenXML is also a good alternative that helps avoid installing MS Excel on Server.The Open XML SDK 2.0 provided by Microsoft simplifies the task of manipulating Open XML packages and the underlying Open XML schema elements within a package. The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages.
Check this out OpenXML: Alternative that helps avoid installing MS Excel on Server

A: I've used with success the following open source projects:

*

*ExcelPackage for OOXML formats (Office 2007)

*NPOI for .XLS format (Office 2003). NPOI 2.0 (Beta) also supports XLSX.
Take a look at my blog posts:
Creating Excel spreadsheets .XLS and .XLSX in C#
NPOI with Excel Table and dynamic Chart

A: Well,
you can also use a third party library like Aspose.
This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case.

A: I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) http://www.aaron-powell.com/linq-to-xml-to-excel

A: Just want to add another reference to a third party solution that directly addresses your issue:  http://www.officewriter.com
(Disclaimer: I work for SoftArtisans, the company that makes OfficeWriter)

A: public class GridViewExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    ///
    /// Replace any of the contained controls with literals
    ///
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

Hi this solution is to export your grid view to your excel file it might help you out

A: Some 3rd party component vendors like Infragistics or Syncfusion provide very good Excel export capabilities that do not require Microsoft Excel to be installed.
Since these vendors also provide advanced UI grid components, these components are particularly handy if you want the style and layout of an excel export to mimic the current state of a grid in the user interface of your application.
If your export is intended to be executed server side with emphasis on the data to be exported and with no link to the UI, then I would go for one of the free open source options (e.g. ExcelLibrary).
I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach.

A: IKVM + POI
Or, you could use the Interop ...

A: Here's a way to do it with LINQ to XML, complete with sample code:
Quickly Import and Export Excel Data with LINQ to XML
It's a little complex, since you have to import namespaces and so forth, but it does let you avoid any external dependencies.
(Also, of course, it's VB .NET, not C#, but you can always isolate the VB .NET stuff in its own project to use XML Literals, and do everything else in C#.)

A: You can create nicely formatted Excel files using this library:
http://officehelper.codeplex.com/documentation

See below sample:
using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"});
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want,
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}

where sample look like this:
private IEnumerable<List<object>> getSample()
{
    var random = new Random();

    for (int loop = 0; loop < 3000; loop++)
    {
        yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
    }
}

A: The simplest and fastest way to create an Excel file from C# is to use the Open XML Productivity Tool.  The Open XML Productivity Tool comes with the Open XML SDK installation.  The tool reverse engineers any Excel file into C# code.  The C# code can then be used to re-generate that file.
An overview of the process involved is:

*

*Install the Open XML SDK with the tool.

*Create an Excel file using the latest Excel client with desired look.  Name it DesiredLook.xlsx.

*With the tool open DesiredLook.xlsx and click the Reflect Code button near the top.

*The C# code for your file will be generated in the right pane of the tool.  Add this to your C# solution and generate files with that desired look.

As a bonus, this method works for any Word and PowerPoint files.  As the C# developer, you will then make changes to the code to fit your needs.
I have developed a simple WPF app on github which will run on Windows for this purpose.  There is a placeholder class called GeneratedClass where you can paste the generated code.  If you go back one version of the file, it will generate an excel file like this:

A: You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB.
Typical example:
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
  conn.Open();
  OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
  cmd.ExecuteNonQuery();
}

EDIT - Some more links:

*

*Hey, Scripting Guy! How Can I Read from Excel Without Using Excel?

*How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET

*Reading and Writing Excel Spreadsheets Using ADO.NET C# DbProviderFactory

A: You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:
ExcelLibrary
This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.
It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.
ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.
You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files). There's also NPOI which works with both.
There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.
Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)
Here are a couple links for quick reference:
ExcelLibrary - GNU Lesser GPL
EPPlus - GNU (LGPL) - No longer maintained
EPPlus 5 - Polyform Noncommercial - Starting May 2020
NPOI - Apache License
Here some example code for ExcelLibrary:
Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.

A: If you make data table or datagridview from the code you can save all data using this simple method.this method not recomended but its working 100%, even you are not install MS Excel in your computer.
try
 {
  SaveFileDialog saveFileDialog1 = new SaveFileDialog();
  saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
  saveFileDialog1.FileName = "Employee Details.xls";
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
  string fname = saveFileDialog1.FileName;
  StreamWriter wr = new StreamWriter(fname);
  for (int i = 0; i <DataTable.Columns.Count; i++)
  {
  wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");
  }
  wr.WriteLine();

  //write rows to excel file
  for (int i = 0; i < (DataTable.Rows.Count); i++)
  {
  for (int j = 0; j < DataTable.Columns.Count; j++)
  {
  if (DataTable.Rows[i][j] != null)
  {
  wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
  }
   else
   {
   wr.Write("\t");
   }
   }
   //go to next line
   wr.WriteLine();
   }
   //close file
   wr.Close();
   }
   }
   catch (Exception)
   {
    MessageBox.Show("Error Create Excel Sheet!");
   }

A: Some time ago, I created a DLL on top of NPOI. It's very simple to use it:
IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople);
MemoryStream memory = engine.Export();

You could read more about it on here.
By the way, is 100% open source. Feel free to use, edit and share ;)

A: To save xls into xlsx format, we just need to call SaveAs method from Microsoft.Office.Interop.Excel library. This method will take around 16 parameters and one of them is file format as well.
Microsoft document: Here
SaveAs Method Arguments
The object we need to pass is like
wb.SaveAs(filename, 51, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, false, false, 1,1, true,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)

Here, 51 is is enumeration value for XLSX
For SaveAs in different file formats you can refer the xlFileFormat

A: I wonder why nobody suggested PowerShell with the free ImportExcel Module; it creates XML-Excel files (xlsx) with ease.
Especially easy when creating Excel-sheets coming from Databases like SQL Server...

A: In my projects, I use some several .net libraries to extract Excel File (both .xls and .xlsx)
To Export data, I frequently use rdlc.
To modify excel files I use (Sample code when I try to set blank Cell A15):
ClosedXML
        //Closed XML
        var workbook = new XLWorkbook(sUrlFile); // load the existing excel file
        var worksheet = workbook.Worksheets.Worksheet(1);
        worksheet.Cell("A15").SetValue("");
        workbook.Save();

IronXL
       string sUrlFile = "G:\\ReportAmortizedDetail.xls";
        WorkBook workbook = WorkBook.Load(sUrlFile);
        WorkSheet sheet = workbook.WorkSheets.First();
        //Select cells easily in Excel notation and return the calculated value
        sheet["A15"].First().Value = "";
        sheet["A15"].First().FormatString = "";

        workbook.Save();
        workbook.Close();
        workbook = null;

SpireXLS (When I try, the library print additional sheet to give information that we use the trial library
            string sUrlFile = "G:\\ReportAmortizedDetail.xls";
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(sUrlFile);
            //Get the 1st sheet
            Worksheet sheet = workbook.Worksheets[0];
            //Specify the cell range
            CellRange range = sheet.Range["A15"];
            //Find all matched text in the range
            CellRange[] cells = range.FindAllString("hi", false, false);
            //Replace text
            foreach (CellRange cell in range)
            {
                cell.Text = "";
            }
            //Save
            workbook.Save();

Jet Oledb
    //ExcelTool Class
    public static int ExcelUpdateSheets(string path, string sWorksheetName, string sCellLocation, string sValue)
    {
        int iResult = -99;
        String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO'";
        OleDbConnection objConn = new OleDbConnection(sConnectionString);
        objConn.Open();
        OleDbCommand objCmdSelect = new OleDbCommand("UPDATE [" + sWorksheetName + "$" + sCellLocation + "] SET F1=" + UtilityClass.ValueSQL(sValue), objConn);
        objCmdSelect.ExecuteNonQuery();
        objConn.Close();

        return iResult;
    }

Usage :
    ExcelTool.ExcelUpdateSheets(sUrlFile, "ReportAmortizedDetail", "A15:A15", "");

Aspose
            var workbook = new Aspose.Cells.Workbook(sUrlFile);
            // access first (default) worksheet
            var sheet = workbook.Worksheets[0];
            // access CellsCollection of first worksheet
            var cells = sheet.Cells;
            // write HelloWorld to cells A1
            cells["A15"].Value = "";
            // save spreadsheet to disc
            workbook.Save(sUrlFile);
            workbook.Dispose();
            workbook = null;

A: I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that
exel cannot open the file bcz file might be coruupted or extension of the file is not compatible.
but if i used .xls for file it work fines
for (int i = 0; i < TotalFile; i++)
{
    Contact.Clear();
    if (innerloop == SplitSize)
    {
        for (int j = 0; j < SplitSize; j++)
        {
            string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();
            Contact.Add(strContact);
        }
        string strExcel = strFileName + "_" + i.ToString() + ".xlsx";
                         File.WriteAllLines(strExcel, Contact.ToArray());
    }
}

also refer link
http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html

A: check this out no need for third party libraries you can simply export datatable data to excel file using this
var dt = "your code for getting data into datatable";
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd")));
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dataColumn in dt.Columns)
            {
                Response.Write(tab + dataColumn.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dataRow in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dataRow[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();